Possible Duplicate:
How to check (via the preprocessor) if a C source file is being compiled as C++ code
I'm trying to find a standard macro which will test whether a header file is being compiled as C or as C++. The purpose of this is that the header may be included by either C or C++ code, and must behave slightly differently depending on which. Specifically:
In C, I need this to be the code:
extern size_t insert (const char*);
In C++, I need this to be the code:
extern "C" size_t insert (const char*);
Additionally, is there a way to avoid putting #ifdef's around every declaration in the header?
Note: We can't include the same header file twice in any program.
To make a header file, we have to create one file with a name, and extension should be (*. h). In that function there will be no main() function. In that file, we can put some variables, some functions etc.
If a header file happens to be included twice, the compiler will process its contents twice. This is very likely to cause an error, e.g. when the compiler sees the same structure definition twice. Even if it does not, it will certainly waste time. This construct is commonly known as a wrapper #ifndef.
In C language, header files contain the set of predefined standard library functions. The “#include” preprocessing directive is used to include the header files with “. h” extension in the program.
It is normal to bracket C header files as follows so they can be used in C++ programs. Check your system header files such as stdio.h and you will probably see this:
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
The answer is to use the macro __cplusplus. In this instance, the most straightforward approach is:
extern
#ifdef __cplusplus
"C"
#endif
size_t insert (const char*);
This macro is part of the C++ standard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With