Is it possible to determine whether a source file is being preprocessed due to an #include statement vs. being preprocessed due to it being a primary source file passed to the compiler?
Basically, I want to be able to write something like the following:
// foo.x:
#if COMPILING_FOO_MODULE
/* FOO code that's only visible when compiling foo.x module */
#endif
/* FOO code that's visible when compiling foo.x module or included in other modules */
// bar.cpp:
#include "foo.x"
...
When preprocessing foo.x, I want both sections of code to be passed on to the compiler, but when preprocessing bar.cpp, I only want the second section to be used:
// foo.x.preprocessed:
/* FOO code that's only visible when compiling foo.x module */
/* FOO code that's visible when compiling foo.x module or included in other modules */
// bar.cpp.preprocessed:
/* FOO code that's visible when compiling foo.x module or included in other modules */
...
I realize I could easily accomplish this by adding #define COMPILING_FOO_MODULE 0 just before the #include, but my goal is to avoid requiring any other code besides the #include to be added to the bar.cpp file.
Including both c and c++ since I assume the answer is the same for both.
EDIT:
To be clear, I understand that having a separate .h and .cpp file exactly solves this problem, and in almost all cases that's the right thing to do. But for various reasons I only want one source file that can be used as both the main module source file and the header file for other modules.
The way this is traditionally done is to split
foo.xinto two files:foo.handfoo.c(orfoo.cpp).foo.hcontains "FOO code that's visible when compiling foo.x module or included in other modules" andfoo.c/foo.cppcontains "FOO code that's only visible when compiling foo.x module".Inside
foo.c/foo.cppyou#include "foo.h"so that it has both sets of code, andbar.cppalso has#include "foo.h".