With gcc, you can use -fpch-preprocess
.
This option allows use of a precompiled header (see Precompiled Headers) together with -E
. It inserts a special #pragma
, #pragma GCC pch_preprocess "filename"
in the output to mark the place where the precompiled header was found, and its filename. When -fpreprocessed
is in use, GCC recognizes this #pragma
and loads the PCH.
This option is off by default, because the resulting preprocessed output is only really suitable as input to GCC. It is switched on by -save-temps
.
You should not write this #pragma
in your own code, but it is safe to edit the filename if the PCH file is available in a different location. The filename may be absolute or it may be relative to GCC’s current directory.
This flag is not available in clang. Instead, you can add -Xclang -pch-through-hdrstop-create
which was inspired by msvc, but the usage is similar to what you get with -fpch-preprocess
: the compiler, when invoked with -include-pch PrecompiledHeader.pch -Xclang -pch-through-hdrstop-use main.cpp.ii
, will consider the first lines in main.cpp.ii
as coming from the precompiled header, and will not complain about duplicate declarations, etc.
Unfortunately, this behavior is not perfect, e.g. on my Mac there is a clash between the declaration
int getchar_unlocked(void);
that comes from line 300 of …/MacOSX.sdk/usr/include/stdio.h and
#define getchar_unlocked() getc_unlocked(stdin)
that comes from line 322 in the same system header file.
For me, the approach proposed by @Leon worked better. I added a twist to it: when compiling the PCH, I add -include my_pragma.h
, which is a one-line file:
#pragma GCC pch_preprocess
My parser (an analog of remove_included_code
) is looking for this pattern and throws away everything before it. This can be easily implemented as awk script.