|
||||
|
Section 32:
|
[32.4] How can I modify my own C header files so it's easier to #include them in C++ code?
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 } #endifNow 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
int main()
{
f(7, 'x', 3.14); // Note: nothing unusual in the call
...
}
Note: Somewhat different guidelines apply for C
headers provided by the system (such as <cstdio>) and for
C headers that you can't change.
Note: #define macros are evil in 4 different ways: evil#1, evil#2, evil#3, and evil#4. But they're still useful sometimes. Just wash your hands after using them. |
|||