compile C and C++ code into one binary in Linux

Sometimes you have a project written in C and you want to add some code (may be open source software) which is provided in C++. So you may want to call a function written in C++ from C. For that purpose, you have to change the function prototype of the concerned C++ function like:

#ifdef __cplusplus
extern "C" {
  int *some_fancy_function(float *im, int width, int height);
#ifdef __cplusplus

The ifdefs are only needed, if you are including the header file containing this code into a C and C++ source file!

When it comes to compiling, use the specific compiler like gcc for C code and g++ for C++ code. Compile each sourcefile(s) into a object file like:

gcc -c myCcode.c
g++ -c myCppcode.cpp
g++ -o myprojectBinary myCcode.o myCppcode.o

The last line will link the object files together.
A good tutorial is found here.

Leave a comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.