4

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:

Common::mystring

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 ?

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190
  • be aware that your static string are global in this case. So they are could create an exception at anytime and can't be catch. I advise you to use function who return a reference of your string. `std::string const &mystring { static std::string const mystring = "IamAwesum"; return mystring}` by this way your object is only construct when needed. – Stargateur Nov 01 '16 at 07:20
  • Can you explain what you mean when you say they could create an exception at any time ? – Rahul Iyer Nov 01 '16 at 08:16
  • [excellent pdf here](https://www.nsnam.org/docs/linker-problems.doc) global constructor is call at the beginning of your program before your main, so you can't handle exception. if you want to do a library with global constructor when your library is loaded she can handle exception when your global object are build. And their are no way to handle an exception when a library is loaded. And the problem can be very hard to find for a user. – Stargateur Nov 01 '16 at 15:22

1 Answers1

3

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.

user4581301
  • 33,082
  • 7
  • 33
  • 54