I am building an application that consists of both a windows driver written in C and a user mode executable in C++. They both use a shared header file to define several macros, constants, enums, etc. In the C++ version, I want to include everything within a namespace, which a feature not supported by the C compiler. Is there certain variable I can check for to use as a preprocessor directive with Visual Studio like in the following example?
#ifdef USING_CPLUSPLUS
namespace mynamespace{
#endif
struct mystruct{
...
};
#ifdef USING_CPLUSPLUS
}
#endif
For the specific example of distinguishing a C++ compiler from a C compiler, the sensible choice is the macro
__cpluspluswhich is defined by the C++ standard to exist, and due toside effects of the reserved name rulesa clause that says so in standard C, will never be predefined by the C compiler.Every compiler has a collection of predefined macros that are occasionally useful for distinguishing among compilation hosts and target platforms. One large repository of such macros is the Predef Project where they are collecting reports on as many combinations of compiler, host, and target as they can.
Edit: Clarifying the reserved nature of
__cplusplusin C: The C standard has always reserved identifiers that begin with two underscores or one underscore followed by a capital letter. For instance, C99 in section 7.1.3 saysand several other clauses carry a footnote that reads in part
So, without any further direction from the standard, in a compliant implementation of a C compiler the name
__cplusplusis reserved for any use. That name was chosen by the implementors of C++ specifically because it was reserved in C, has a clear meaning, and was not known to have been defined by any C implementation.However, by C99 the standards committee had decided to make sure that no C implementation damaged the obvious utility of a macro that could be used to distinguish a C compilation from a C++ compilation. In C99 section 6.10.8 they write:
Its hard to get more clear than that.