view raw
John John - 6 months ago 29
C++ Question

What happens to a .h file that is not included in a target during compilation?

I have a "Common.h" file, which stores all the strings are reused across my project.

namespace Common{
static const std::string mystring = "IamAwesum";

So in any file that needs a particular string I include the file:

include "Common.h"

and then where I need the string I use:


Now I noticed in Xcode, that none of the ".h" files are included in the target. But it seems my program works fine as expected. Can someone explain what happens to .h files? How does this work ? Is it because the file that "includes" "Common.h" has a copy of all the data ?


A header is not compiled (exceptions being pre-compiled headers, a common build optimization technique, and by mistake), but is instead, as OP suspected, copied into the files which use them.

From [cpp.include] in the C++ Standard

A preprocessing directive of the form

# include " q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

The included file is pasted into the file being compiled where the #include directive is, replacing the #include.

So if a file is not included, it never gets substituted into a file being compiled and absolutely nothing happens to the file.

An included file doesn't need to be listed anywhere in a project, target makefile, or what-have-you. The inclusion of the file is strictly up to the cpp file doing the including, though often a list of places to look for included headers will be present to abstract away the toolchain and libraries from the source code.