Mixing C and C++ files in a C++ project

Hi

In this post I’ll talk about what to do when we are working a in a project with both kind of files, I mean, when we mix C source files with C++ source files in a C++ project.

The C++ compiler appends some (invisible for us) characteres to each function and method it finds in a project. It makes sense because there must be a way to distinguish overloaded methods from each one. But in a project with both kind of source files, the gcc compiler is called to compile the C ones, whilst the g++ compiler is called for the the other ones. The linker is the problem here: as it is a C++ project, it expects that every compiled file is following the C++ name rules; however, those compiled with the gcc compiler don’t, so no matter you know that the files and functions are where the linker expect to be, it will throw an error:

... undefined reference to ...

Don’t you hate that? I’m sick of it!! But there is a simple way to get our project to compile: We must advice the compiler that our C source file must be compiled as a C++ one. To achieve our goal we need to embrace the function declarations (the functions declarations are normally in the .h file) with these preprocessor instructions:

#ifdef __cplusplus
extern "C" {
#endif

our method definitions are here ...

#ifdef __cplusplus
}
#endif

extern “C” is telling the C++ compiler that it must be aware that they are C files, not C++ files. In C++ projects, the macro __cplusplus is set automatically by the compiler, so the extern “C” modifier won’t exist when compiling a C project.

Don’t forget to repeat this procedure for ALL the header files that point to C source files in your project.

In the next picture you can see a real file (small PWM driver) for a C++ project of my own:

cpp-c-GVIM

As always, your comments are appreciated.

Anuncios

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s