40

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.

Timmetje
  • 7,641
  • 18
  • 36
SadSeven
  • 1,247
  • 1
  • 13
  • 20

3 Answers3

62

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++.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 21
    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). – Medinoc Jul 03 '13 at 12:38
  • 1
    why would you add C++ code to a C header?! the extern should live somewhere in a cpp file – Christoph Sep 06 '20 at 08:32
21

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
vallentin
  • 23,478
  • 6
  • 59
  • 81
Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • 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. https://stackoverflow.com/a/67896193/1599699 – Andrew Jun 09 '21 at 01:02
18

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.

unwind
  • 391,730
  • 64
  • 469
  • 606