Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

07
Dec

How to inlcude C header files in C++

Related Blog Items

There are two ways to do this

1)

If you are including a C header file that isn’t provided by the system, you may need to wrap the #include line in an extern “C” { /*…*/ } construct. This tells the C++ compiler that the functions declared in the header file are C functions.

// This is C++ code

extern ”C” {
// Get declaration for f(int i, char c, float x)
#include ”my-C-code.h”
}
2)

If you are including a C header file that isn’t provided by the system, and if you are able to change the C header, you should strongly consider adding the extern “C” {…} logic inside the header to make it easier for C++ users to #include it into their C++ code. Since a C compiler won’t understand the extern “C” construct, you must wrap the extern “C” { and } lines in an #ifdef so they won’t be seen by normal C compilers.

Step #1: Put the following lines at the very top of your C header file (note: the symbol __cplusplus is #defined if/only-if the compiler is a C++ compiler):

#ifdef __cplusplus
extern ”C” {
#endif

Step #2: Put the following lines at the very bottom of your C header file:

#ifdef __cplusplus
}
#endif

Now you can #include your C header without any extern “C” nonsense in your C++ code:

// This is C++ code

// Get declaration for f(int i, char c, float x)
#include ”my-C-code.h”   // Note: nothing unusual in #include line

Popularity: 4%

You need to log on to convert this article into PDF


Related Blog Items

No Comments

No comments yet.

Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image