In this noncompliant code example, the function f () is defined in the header file. However, including a header file in more than one translation unit may violate a single definition rule. This usually indicates that incorrect diagnostics are generated at link time because more than one function with the same name is defined. This noncompliant code example attempts to resolve link-time errors by defining f () in an unnamed namespace. However, multiple unique f () definitions are generated for the generated executable file. If a.h is included in many translation units, the link time will be longer, the executable file will grow larger, and the performance may be degraded.
In product quality C ++ code, header files are often used as a means of sharing code between translation units. The header file is a file inserted into the translation unit via the #include directive. Do not define an unnamed namespace in the header file. Defining an unnamed namespace in the header file can produce amazing results. Because of the default internal link, each translation unit defines a unique instance of a member of the unnamed namespace being used in that translation unit. This leads to unpredictable results, possibly causing the executable to bloat or to accidentally cause undefined behavior due to a single definition rule (ODR) violation.
The C ++ code file (extension .cpp) is not the only file common to C ++ programs. Another type of file is called a header file, sometimes called an include file. Although the extension of the header file is usually .h, you can see that the extension is .hpp or has no extension at all. The purpose of the header file is to save declarations of other files being used. This program displays "Hello, world!" With cout on the console. However, since this program does not define cout, how does the compiler recognize what cout is? The answer is that cout is declared in the header file "iostream". When using #include lines, you need to copy everything named "iostream" in the header file to the include file. This makes the contents of the header file available in the code file.