Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use C code in C++

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.

like image 338
SadSeven Avatar asked Jul 03 '13 12:07

SadSeven


People also ask

Can I use C code in C++?

If the C++ compiler provides its own versions of the C headers, the versions of those headers used by the C compiler must be compatible. Oracle Developer Studio C and C++ compilers use compatible headers, and use the same C runtime library. They are fully compatible.

What is C code used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


2 Answers

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

like image 156
RichieHindle Avatar answered Sep 20 '22 08:09

RichieHindle


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 
like image 27
Mats Petersson Avatar answered Sep 18 '22 08:09

Mats Petersson