How do I mix C and C++ source code?
There are two ways to combine C and C++ code:
Separate C and C++ source and header files.
-
Include C header files in your C++ code by wrapping them in an
extern "C"
block. The C++ compiler will automatically take care of the name mangling and calling conventions differences between C and C++. The functions and variables from the C source code can be used in the C++ code. -
Compile the C and C++ source files separately.
-
Link all object files together.
Example
- c_hdr.h
-
Declaration of
c_foo
C function - c_src.c
-
Definition of
c_foo
C function - main.cpp
extern "C" {
// Include C header file
#include "c_hdr.h"
}
int main() {
// Call the C function from the C++ code
c_foo(42);
return 0;
}
C functions/variables in the C++ source files
-
Declare the C functions/variables in an
extern "C"
block. The functions declared within it will use the C linkage, which means they will have C naming and calling conventions and will be callable/accessible from C++ code.
Example
extern "C" {
// Declaration of a C function
void c_foo(int arg);
}
// Definition of the C function
void c_foo(int arg) {
// Do not use arg parameter
(void)arg;
}
int main() {
// Call the C function from C++ code
c_foo(42);
return 0;
}