C++ library in a C application
Posted: aprile 10th, 2012 | Author: Francesco Apollonio | Filed under: C/C++, English, Guide, Programmazione | Tags: code tips, gcc, Guide, linker, linux, makefile, qemu, systemc, varie | No Comments »
This is the second part of the integration of a SystemC module into Qemu. SystemC is C++ so I’ve had lots of problems trying to link my library (that is a multiprocessor simulator written in SystemC) with Qemu, because this is written in pure C.
The first rule that you have to remember when you want to link a C++ library with a C application is to wrap the functions that you want to export with the construct “extern C” . This tells to the C++ compiler to use the standard C name mangling for a function or a group of functions. You can use it in the following way:
extern "C" void function1(int a);
void function1(int a) { /* my function code */ }
In this example function1 can be used in a C application even if it is C++ code. Note that the object for this file must be created using a C++ compiler.
After you can use function1 in any functions written in C (remember to create and to include an header or to use “extern void function1″ in your C code).
The last important rule is to create the binary, linking all different object files using a C++ linker.
In my project I’ve added another C++ file in Qemu with something like the function1 explained before, and I’ve to edit Qemu’s Makefile to compile the new C++ file and create the final executable using C++ linker and not a C one.
Now I can use my C++ code in a C application.








Leave a Reply