How Does Compiler know addition , subtraction operators while compiling the code? - c++

I have made the simple program in cplus like this -
main()
{
int a=5;
int b=8;
int c;
c= a+b;
cout<<c<<endl;
return 0;
}
I get the output as 13 which is correct.
I want to know How g++ compiler knows about "+" operator ?
Is there any method defined in header file for this operator , like the other keywords are defined in standard libraries.

There is no method for basic types such as int short char double etc. Basic operation for these types is built into compiler. So compiler when it sees these operations on basic types converts it directly to assembly. So here is an example:
If you want to see assembly output do following gcc -S myfile.c or for c++ g++ -S myfile.cpp

Related

Put C++ class in C-struct for for use in C++ function (C/C++ mixed code)

NOTE: This is not about C/C++ linkage or the extern keyword. Please read carefully before associating my question with seemingly similar questions, thank you!
I think this is a somewhat unusual problem as I didn't find anything on this while browsing the web.
I'm programming an embedded system. The main module is written in C while a submodule is written in C++. To illustrate this:
submodule.hpp
/ \
/ \
main.c submodule.cpp
Now I want to hold on to the data that is used by the C++-submodule and contain it in a static variable in my main script so I can call submodule functions from main and provide context data with every call. But that data must also contain a class as it is used by the submodule functions, but of course C doesn't know how to deal with classes. So I have to covertly put a class into my C-struct without main.c-script noticing (giving me an error). How could I achieve this?
I figured something like this could work:
struct data_for_cpp_submodule {
int a;
int b;
void *class;
}
And then casting the void pointer "class" back to the appropriate class so I can work with it in the C++ script. Could this work or am I going about it completely the wrong way?
Please, note that OP emphasized:
The main module is written in C while a submodule is written in C++.
IMHO, it's completely fine to add a C binding for the C++ submodule, so that it can be used in C code.
The example of OP (enhanced a bit to make it an MCVE):
C++ code for submodule:
header submodule.hpp:
#ifndef SUB_MODULE_HPP
#define SUB_MODULE_HPP
class Test {
private:
int a = 0;
int b = 0;
public:
Test() = default; // default constructor
Test(int a, int b): a(a), b(b) { } // value constructor
Test(Test&) = delete; // say: copy constructor disabled
Test& operator=(Test&) = delete; // say: copy assignment disabled
public:
int exec() const;
};
#endif // SUB_MODULE_HPP
source submodule.cpp:
#include "submodule.hpp"
int Test::exec() const { return a + b + 42; }
C Binding for submodule:
header: submodule.h
#ifndef SUB_MODULE_H
#define SUB_MODULE_H
#ifdef __cplusplus
extern "C" {
#endif
struct TestC_;
typedef struct TestC_ TestC; // opaque structure
extern TestC* testNew();
extern TestC* testNewValues(int a, int b);
extern void testDelete(TestC *pTest);
extern int testExec(TestC *pTest);
#ifdef __cplusplus
}
#endif
#endif // SUB_MODULE_H
source submoduleC.cpp:
#include "submodule.h"
#include "submodule.hpp"
TestC* testNew() { return (TestC*)new Test(); }
TestC* testNewValues(int a, int b) { return (TestC*)new Test(a, b); }
void testDelete(TestC *pTest) { delete (Test*)pTest; }
int testExec(TestC *pTest) { return ((Test*)pTest)->exec(); }
Last but not least: A sample C program using submodule:
#include <stdio.h>
#include "submodule.h"
int main(void)
{
TestC *pTest = testNew();
printf("pTest->exec(): %d\n", testExec(pTest));
testDelete(pTest);
pTest = testNewValues(123, -123);
printf("pTest->exec(): %d\n", testExec(pTest));
testDelete(pTest);
}
How it has to be compiled and linked with g++/gcc:
$ ## compile C++ code
$ g++ -std=c++17 -O2 -Wall -pedantic -c submodule.cpp submoduleC.cpp
$ ## compile C code
$ gcc -std=c11 -O2 -Wall -pedantic -lstdc++ main.c submodule.o submoduleC.o
$ ## test
$ ./a.out
Output:
testExec(pTest): 42
testExec(pTest): 42
Demo on coliru
The most notable part might be the opaque structure:
struct TestC_;
typedef struct TestC_ TestC; // opaque structure
(This is what I learnt from other C bindings before I started to write my own.)
It might be surprising that the opaque structure is actually an incomplete structure but that's intentional.
The opaque structure is intended to be used as pointer only in C. It's not intended to allow dereferencing of any contents (and, for an incomplete structure, this is merely denied by the compiler). It's only purpose is to "tunnel" a pointer to a C++ Test instance through the C code.
In the C binding of Test (submoduleC.cpp), TestC* is simply converted to Test* (and vice versa) where necessary.
Hint:
I had to link -lstdc++ (the standard C++ library). Otherwise, I got complaints about undefined references for the operators new and delete:
submoduleC.o: In function `testNew':
submoduleC.cpp:(.text+0xa): undefined reference to `operator new(unsigned long)'
submoduleC.o: In function `testNewValues':
submoduleC.cpp:(.text+0x30): undefined reference to `operator new(unsigned long)'
submoduleC.o: In function `testDelete':
submoduleC.cpp:(.text+0x4b): undefined reference to `operator delete(void*, unsigned long)'
collect2: error: ld returned 1 exit status
Other thoughts (but probably not that relevant):
I remember a prominent framework which
is written in C
and provides a C++ API (aka. C++ binding).
I'm talking about GTK+ and gtkmm (its C++ binding).
Thereby, it should be mentioned that GTK+ is actually an OOP library – providing object-oriented classes implemented in C. (I'm uncertain whether this fact makes things easier or harder concerning the C++ binding.)
Both are Open Source projects. Hence, everybody can have a look at it how did they do. I once had a look and was impressed…
This aside, I always would recommend the opposite: writing a library in C++ and adding a C binding as this appears much easier to me.
We always did this in Windows for multiple reasons:
to achieve that DLLs compiled with different versions of Visual Studio can be linked together. (Until soon, this was nearly impossible with C++ but now, I believe, I read about an ABI introduced by Microsoft which may it make possible.)
to provide a base for bindings in other languages like e.g. C#.

c and c++ function declaration & definition : specifying data type

I am working on porting c code to c++. The below C program compiles successfully. But in c++, it throws an error. I know its really basic thing. I've more than 100 functions declared in this way. Is there any flag we can add to compile successfully instead of modifying all the functions.
OS: Windows
IDE: Visual Studio
int sum(m,n)
int m,n;
{
return m+n;
}
This is very old style C. Nobody should have been using this for the last 30 years. You can't compile this with a C++ compiler. There are no compiler flags whatsoever for this, at least in the compilers I'm aware of (clang, gcc, microsoft compilers).
You should transform all functions that have the form
int sum(m,n)
int m,n;
{
return m+n;
}
int to the form
int sum(int m, int n)
{
return m+n;
}
If you have 100 functions it should be doable.
But there may be many other problems because C++ is not an exact superset of C.
This SO article may be interesting for you: Function declaration: K&R vs ANSI

Is there any way to transform strings into compileable/runnable code?

For example, suppose we have a string like:
string x = "for(int i = 0; i < 10; i++){cout << \"Hello World!\n\";}"
What is the simplest way to complete the following function definition:
void do_code(string x); /* given x that's valid c++ code, executes that code as if it were written inside of the function body */
The standard C++ libraries do not contain a C++ parser/compiler. This means that your only choice is to either find and link a C++ compiler library or to simply output your string as a file and launch the C++ compiler with a system call.
The first thing, linking to a C++ compiler, would actually be quite doable in something like Visual Studio for example, that does indeed have DLL libraries for compiling C++ and spitting out a new DLL that you could link at runtime.
The second thing, is pretty much what any IDE does. It saves your text-editor stuff into a C++ file, compile it by system-executing the compiler and run the output.
That said, there are many languages with build-in interpreter that would be more suitable for runtime code interpretation.
Not directly as you're asking for C++ to be simultaneously compiled and interpreted.
But there is LLVM, which is a compiler framework and API. That would allow you to take in this case a string containing valid C++, invoke the LLVM infrastructure and then afterwards use a LLVM-based just in time compiler as described at length here. Keep in mind you must also support the C++ library. You should also have some mechanism to map variables into your interpreted C++ and take data back out.
A big but worthy undertaking, seems like someone might have done something like this already, and maybe Cling is just that.
Use the Dynamic Linking Loader (POSIX only)
This has been tested in Linux and OSX.
#include<fstream>
#include<string>
#include<cstdlib>
#include<dlfcn.h>
void do_code( std::string x ) {
{ std::ofstream s("temp.cc");
s << "#include<iostream>\nextern \"C\" void f(){" << x << '}'; }
std::system( "g++ temp.cc -shared -fPIC -otemp.o" );
auto h = dlopen( "./temp.o", RTLD_LAZY );
reinterpret_cast< void(*)() >( dlsym( h, "f" ) )();
dlclose( h );
}
int main() {
std::string x = "for(int i = 0; i < 10; i++){std::cout << \"Hello World!\\n\";}";
do_code( x );
}
Try it online! You'll need to compile with the -ldl parameter to link libdl.a. Don't copy-paste this into production code as this has no error checking.
Works for me:
system("echo \"#include <iostream> \nint main() { for(int i = 0; i < 10; i++){std::cout << i << std::endl;} }\" >temp.cc; g++ -o temp temp.cc && ./temp");

micro optimisation using and operator

Suppose this situation, you have a function that return void and the method is mostly gonna be the only statement of a if
if(condition)
someVoidMethod();
Since certain language will not continue the evaluation of a boolean expression of concatenated and's if any of them return false. We are wondering what are the optimization implied by changing the return type to int (or bool/boolean) and writing this instead
condition && someIntMethod();
without any assignation.
We understand that programmers shouldn't focus in micro-optimization but it's really just for academic purpose.
The compiler will generate the same code for both alternatives with any reasonable level of optimization. The logic behind both statements is exactly the same, because && produces a branching behavior in both C and C++ for short-circuiting.
I verified this using two programs:
Program 1:
#include <stdio.h>
int foo() {printf("foo\n");}
int main() {
int i;
scanf("%d", &i); // Prevent from optimizing out the "if"
if (i) foo();
return 0;
}
Program 2:
#include <stdio.h>
int foo() {printf("foo\n");}
int main() {
int i;
scanf("%d", &i); // Prevent from optimizing out the "if"
i && foo();
return 0;
}
I compiled both programs on my mac with -O3 level *, and compared the output:
gcc -c -O3 a.c
gcc -c -O3 b.c
cmp a.o b.o
cmp produced no output, so the files were identical. Compiling without -O3 flag produced different outputs.
* gcc --version command prints
Apple LLVM 5.0 (clang 500.2.79) (based on llvm 3.3svn)
It would take a smarter compiler to figure out that it can ignore the return value from someIntMethod (although I suspect most compilers would do so). But more seriously if the function isn't inline it would have to take extra cycles to pass the value back even if it's going to be discarded, so the first is possibly more efficient.
That said the only way to know for sure is to compile both with your compiler and options consistent with a release build and see what assembly it generates.

Calling C++ (not C) from Common Lisp?

I am wondering if there is some way to call C++ code from Common Lisp (preferably portably, and if not, preferably in SBCL, and if not, well, then Clozure, CLisp or ECL).
The C++ would be called inside loops for numeric computation, so it would be nice if calls were fast.
CFFI seems to not support this:
"The concept can be generalized to
other languages; at the time of
writing, only CFFI's C support is
fairly complete, but C++ support is
being worked on."
(chapter 4 of the manual)
SBCL's manual doesn't mention C++ either; it actually says
This chapter describes SBCL's
interface to C programs and libraries
(and, since C interfaces are a sort of
lingua franca of the Unix world, to other programs and libraries in
general.)
The C++ code uses OO and operator overloading, so it really needs to be compiled with g++.
And as far as I know, I can have a C++ main() function and write wrappers for C functions, but not the other way around -- is that true?
Anyway... Is there some way to do this?
Thank you!
After compiling, most C++ functions actually boil down to regular C function calls. Due to function overloading and other features, C++ compilers use name mangling to distinguish between similarly named functions. Given an object dump utility and sufficient knowledge about your C++ compiler, you can call C++ code directly from the outside world.
Having said that though, you may find it easier to write a C-compatible layer between Lisp and your C++ code. You would do that using extern "C" like this:
extern "C" Foo *new_Foo(int x)
{
return new Foo(x);
}
This makes the new_Foo() function follow the C calling convention so that you can call it from external sources.
The main difference in calling C++ functions instead of C functions apart from the name mangling are the 'hidden' features like this pointers that are implicitly passed to member functions. The C runtime layer doesn't know anything about these, implicit type conversions and other fun C++ features, so if you intend to call C++ through a C interface, you might have to fake these features if necessary.
Assuming that you can hold at least a void * to the object you intend to call and the data it requires, you can degrade the following C++ call
matrix->multiply(avector);
to a C call if you create a C wrapper function:
extern "C"
void matrix_multiply(void *cpp_matrix, void *cpp_vector) {
reinterpret_cast<matrix_type *>(cpp_matrix)->multiply(reinterpret_cast<vector_type *>(cpp_vector);
}
Obviously the function matrix_multiply would sit in the C++ source code and compiled as such but it does expose a C interface to the outside world. As long as you can interact with the opaque pointers, you're OK with the translation shims above.
Admittedly this is not necessarily the most elegant solution for a problem like this but I've used it in the past in situations like yours.
The other option would be to make the C++ calls directly by treating them as C calls with additional parameters and supplying all the required information yourself, but that does move you into the realm of compiler-specific code very quickly. Basically, you would still be holding the opaque pointers to C++ objects, but you'd have to work out the mangled name of the function you want to call. Once you've got that function name, you'll have to supply the this pointer (which is implicit in C++ and semi-implicit in the example above) and the correct parameters and then call the function. It can be done but as mentioned, puts you deeply in to the realm of compiler and even compiler-version specific behaviour.
Oh, wait!
It seems that there is a trick I can use!
I write a wrapper in C++, declaring wrapper functions extern "C":
#include "lib.h"
extern "C" int lib_operate (int i, double *x) {
...
}
The header file lib.h, which can be called from both C and C++, is:
#if __cplusplus
extern "C" {
#endif
int lib_operate (int i, double *x);
#if __cplusplus
}
#endif
Then compile with:
g++ -c lib.cpp
gcc -c prog.c
gcc lib.o prog.o -lstdc++ -o prog
Seems to work for a toy example! :-)
So, in Common Lisp I'd call the wrapper after loading libstdc++.
Anyway, thank you for your answers!
Update 2021:CL-CXX-JIT which handles most of the work on the lisp side.
Example:
(ql:quickload :cxx-jit)
(in-package cxx-jit)
(from '("<cmath>") 'import '("static_cast<double(*)(double)>(std::sin)" . "cpp-sin"))
(cpp-sin 0d0)
(from nil 'import "struct C{ auto hi(){return \"Hello, World\\n\";} auto bye(){return \"Bye\";} };" '("&C::bye" . "bye") '("&C::hi" . "hi") '("[](){static C x; return x;}" . "cc"))
(cc)
(hi *)
(bye **)
You can use cl-cxx which is like writing pybind11 for python.
example in c++ 'std >= c++14', compiled as shared lib:
#include <string>
#include "clcxx/clcxx.hpp"
class xx {
public:
xx(int xx, int yy) : y(yy), x(xx) {}
std::string greet() { return "Hello, World"; }
int y;
int x;
};
std::string greet() { return "Hello, World"; }
int Int(int x) { return x + 100; }
float Float(float y) { return y + 100.34; }
auto gr(std::complex<float> x) { return x; }
std::string hi(char* s) { return std::string("hi, " + std::string(s)); }
void ref_class(xx& x) { x.y = 1000000; }
CLCXX_PACKAGE TEST(clcxx::Package& pack) {
pack.defun("hi", F_PTR(&hi));
pack.defun("test-int", F_PTR(&Int));
pack.defun("greet", F_PTR(&greet));
pack.defun("test-float", F_PTR(&Float));
pack.defun("test-complex", F_PTR(&gr));
pack.defun("ref-class", F_PTR(&ref_class));
pack.defclass<xx, false>("xx")
.member("y", &xx::y)
.defmethod("greet-from-class", F_PTR(&xx::greet))
.constructor<int, int>();
}
usage in lisp:
(cffi:use-foreign-library my-lib)
(cxx:init)
(cxx:add-package "TEST" "TEST")
(test:greet)
(setf my-class (test:create-xx2 10 20))
(test:y.get myclass)
That would take care of all conversions, extern "C", ... for you.
Depending on your C++ ABI, your wrapper (lib_operate above) might need to somehow handle any C++ exceptions that might occur. If your ABI does table-drive exception handling, unhandled exceptions will simply crash the (Lisp) process. If it instead does dynamic registration, you might not even notice that anything went wrong. Either way, it's bad.
Or, if you've got the no-throw guarantee for the wrapped code, you can ignore all this.