Some Java Programmer Some Java Programmer - 1 month ago 5
C++ Question

Does C++ Support Global Headers At Compile Time?

When attempting to compile an externally provided C++ codebase, I've encountered a confusing problem:

Several of the header files are missing

#include <MyLibrary.h>
, where MyLibrary is an obvious dependency that is simply missing, and preventing compilation.

My question is:
When compiling C++ code, is there a way to automatically include a dependency header file, without needing to #include it in each of the .h/.cpp files where it is required? In other words, a way to provide the C++ preprocessor a list of header files to automatically include when compiling all of the source code?

I understand that this is probably a very bad idea, but I'm trying to determine if the code I've been provided is simply broken, or if there's some way it could be compiled without manually fixing each file with missing dependencies.

Answer

The C++ language standard does not support "global headers", but individual compilers do.

It's called a forced include.

With Visual C++ it's the option /FI, and with g++ it's option -include.


With Visual C++, however, the usual way to include common headers is to place those includes in a file called stdafx.h, and include that file in every translation unit, first of all. That's part of Visual C++'s precompiled header support. It's problematic because when it's turned on (and it's on by default in a Visual Studio project) it changes the preprocessing rules so that some standard code may not compile, but it can speed up larger builds considerably.