How to use C code in C++

42,898

Solution 1

Yes, you can include C headers in C++ code. It's normal to add this:

#ifdef __cplusplus
extern "C"
{
#endif

// C header here

#ifdef __cplusplus
}
#endif

so that the C++ compiler knows that function declarations etc. should be treated as C and not C++.

Solution 2

If you are compiling the C code together, as part of your project, with your C++ code, you should just need to include the header files as per usual, and use the C++ compiler mode to compile the code - however, some C code won't compile "cleanly" with a C++ compiler (e.g. use of malloc will need casting).

If on, the other hand, you have a library or some other code that isn't part of your project, then you do need to make sure the headers are marked as extern "C", otherwise C++ naming convention for the compiled names of functions will apply, which won't match the naming convention used by the C compiler.

There are two options here, either you edit the header file itself, adding

#ifdef __cplusplus 
extern "C" {
#endif

... original content of headerfile goes here. 

#ifdef __cplusplus 
}
#endif

Or, if you haven't got the possibility to edit those headers, you can use this form:

#ifdef __cplusplus 
extern "C" {
#endif
#include <c_header.h>
#ifdef __cplusplus 
}
#endif

Solution 3

Yes, but you need to tell the C++ compiler that the declarations from the header are C:

extern "C" {
#include "c-header.h"
}

Many C headers have these included already, wrapped in #if defined __cplusplus. That is arguably a bit weird (C++ syntax in a C header) but it's often done for convenience.

Share:
42,898
SadSeven
Author by

SadSeven

Updated on July 09, 2022

Comments

  • SadSeven
    SadSeven almost 2 years

    Just a small question: Can C++ use C header files in a program?

    This might be a weird question, basically I need to use the source code from other program (made in C language) in a C++ one. Is there any difference between both header files in general? Maybe if I change some libraries... I hope you can help me.

  • Medinoc
    Medinoc almost 11 years
    Note that it does not mean "compile this code as C". It only means that all symbols between the brackets have C linkage (which means, among other things, not to perform C++ name mangling on them).
  • Christoph
    Christoph over 3 years
    why would you add C++ code to a C header?! the extern should live somewhere in a cpp file
  • Andrew
    Andrew almost 3 years
    In my case, even though the ".c" file I included did this properly, I still had issues, until I renamed my ".c" file to ".cpp"; then everything worked just fine. stackoverflow.com/a/67896193/1599699