Using C and C++ Together

CodeBlocks projects can have a mix of C, C++, and even assembly files. The GCC compiler compiles a file as either C or C++ depending on its file extension: a C file has the .c extension and a C++ file has the .cpp extension. A project can have a mixture of C and C++ files. Functions defined in a .c C file cannot use C++ features such as calling a class function. However, it is easy to allow non-class functions in C++ files to interact with C functions in C files.

 

NOTE: Be sure to keep this in mind: if you write a function in a .cpp file, then it is a C++ function unless you declare it as extern “C” (see below), and it has a “funny” internal name, different from the name you write [3]. This is why the following practices must be observed for C and C++ functions to be able to inter-operate together. This also means that if you are writing an interrupt handler (see later section on “Writing an Interrupt Handler”), you must be careful to make sure that it is a C function by 1) either defining in a .c file, or 2) using the extern “C”.

 

Defining a function in a C++ file with the extern “C” keywords means that the function is a C function and can be called by other C functions in C files. NOTE: a C function in a .cpp file can still access global C++ objects declared in the file.

In a C++ file:

 

// declaration of functions defined in a C++ .cpp file that are to

// be accessed by functions defined in a C .c file.

extern “C” int cpp_func1(void);    

extern “C” int cpp_func2(void);

 

// definition

extern “C” int cpp_func1(void)

      {

      return 1;

      }

 

For functions in a C++ file to access C functions in a C file, similar extern declarations must be used:

 

// in a C++ .cpp file,

// declaration of functions defined in a C .c

extern “C” int c_func1(void);

extern “C” int c_func2(void);

 

 

Multiple such declarations in a C++ file can be grouped with a set of {} in an extern “C” declaration:

 

extern “C” {

      int c_func1(void);

      int c_func2(void);

}

 

A C-only header file can be similarly #include’d:

 

extern “C” {

#include “c_header.h”

}

In a C file

To access C functions defined in a C++ .cpp file, that are declared as above, just declare these functions normally:

 

extern int cpp_func1(void);

extern int cpp_func2(void);