{"id":32,"date":"2007-06-03T09:29:36","date_gmt":"2007-06-03T17:29:36","guid":{"rendered":"https:\/\/2.zoppoz.workers.dev:443\/http\/www.learncpp.com\/?p=32"},"modified":"2025-02-27T00:16:12","modified_gmt":"2025-02-27T08:16:12","slug":"header-files","status":"publish","type":"post","link":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/header-files\/","title":{"rendered":"2.11 &#8212; Header files"},"content":{"rendered":"<p>In lesson <a href=\"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/programs-with-multiple-code-files\/\">2.8 -- Programs with multiple code files<\/a>, we discussed how programs can be split across multiple files.  We also discussed how forward declarations are used to allow the code in one file to access something defined in another file.<\/p>\n<p>When programs contain only a few small files, manually adding a few forward declarations to the top of each file isn&#8217;t too bad.  However, as programs grow larger (and make use of more files and functions), having to manually add a large number of (possibly different) forward declarations to the top of each file becomes extremely tedious.  For example, if you have a 5 file program, each of which requires 10 forward declarations, you&#8217;re going to have to copy\/paste in 50 forward declarations.  Now consider the case where you have 100 files and they each require 100 forward declarations.  This simply doesn&#8217;t scale!<\/p>\n<p>To address this issue, C++ programs typically take a different approach.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Header files<\/p>\n<p>C++ code files (with a .cpp extension) are not the only files commonly seen in C++ programs.  The other type of file is called a <strong>header file<\/strong>.  Header files usually have a .h extension, but you will occasionally see them with a .hpp extension or no extension at all.<\/p>\n<p>Conventionally, header files are used to propagate a bunch of related forward declarations into a code file.<\/p>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>Header files allow us to put declarations in one place and then import them wherever we need them.  This can save a lot of typing in multi-file programs.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Using standard library header files<\/p>\n<p>Consider the following program:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; \"Hello, world!\";\r\n    return 0;\r\n}<\/code><\/pre>\n<p>This program prints &#8220;Hello, world!&#8221; to the console using <em>std::cout<\/em>.  However, this program never provided a definition or declaration for <em>std::cout<\/em>, so how does the compiler know what <em>std::cout<\/em> is?<\/p>\n<p>The answer is that <em>std::cout<\/em> has been forward declared in the &#8220;iostream&#8221; header file.  When we <code>#include &lt;iostream&gt;<\/code>, we&#8217;re requesting that the preprocessor copy all of the content (including forward declarations for std::cout) from the file named &#8220;iostream&#8221; into the file doing the #include.<\/p>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Key insight<\/p>\n<p>When you <code>#include<\/code> a file, the content of the included file is inserted at the point of inclusion.  This provides a useful way to pull in declarations from another file.\n<\/div>\n<p>Consider what would happen if the <em>iostream<\/em> header did not exist.  Wherever you used <em>std::cout<\/em>, you would have to manually type or copy in all of the declarations related to <em>std::cout<\/em> into the top of each file that used <em>std::cout<\/em>!  This would require a lot of knowledge about how <em>std::cout<\/em> was declared, and would be a ton of work.  Even worse, if a function prototype was added or changed, we&#8217;d have to go manually update all of the forward declarations.<\/p>\n<p>It&#8217;s much easier to just <code>#include &lt;iostream&gt;<\/code>!<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Using header files to propagate forward declarations<\/p>\n<p>Now let&#8217;s go back to the example we were discussing in a previous lesson.  When we left off, we had two files, <em>add.cpp<\/em> and <em>main.cpp<\/em>, that looked like this:<\/p>\n<p>add.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int add(int x, int y)\r\n{\r\n    return x + y;\r\n}<\/code><\/pre>\n<p>main.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;iostream&gt;\r\n\r\nint add(int x, int y); \/\/ forward declaration using function prototype\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; \"The sum of 3 and 4 is \" &lt;&lt; add(3, 4) &lt;&lt; '\\n';\r\n    return 0;\r\n}<\/code><\/pre>\n<p>(If you&#8217;re recreating this example from scratch, don&#8217;t forget to add <em>add.cpp<\/em> to your project so it gets compiled in).<\/p>\n<p>In this example, we used a forward declaration so that the compiler will know what identifier <em>add<\/em> is when compiling <em>main.cpp<\/em>.  As previously mentioned, manually adding forward declarations for every function you want to use that lives in another file can get tedious quickly.<\/p>\n<p>Let&#8217;s write a header file to relieve us of this burden.  Writing a header file is surprisingly easy, as header files only consist of two parts:<\/p>\n<ol>\n<li>A <em>header guard<\/em>, which we&#8217;ll discuss in more detail in the next lesson (<a href=\"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/header-guards\/\">2.12 -- Header guards<\/a>).<\/li>\n<li>The actual content of the header file, which should be the forward declarations for all of the identifiers we want other files to be able to see.<\/li>\n<\/ol>\n<p>Adding a header file to a project works analogously to adding a source file (covered in lesson <a href=\"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/programs-with-multiple-code-files\/\">2.8 -- Programs with multiple code files<\/a>).<\/p>\n<p>If using an IDE, go through the same steps and choose &#8220;Header&#8221; instead of &#8220;Source&#8221; when asked.  The header file should appear as part of your project.<\/p>\n<p>If using the command line, just create a new file in your favorite editor in the same directory as your source (.cpp) files.  Unlike source files, header files should <em>not<\/em> be added to your compile command (they are implicitly included by #include statements and compiled as part of your source files).<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Prefer a .h suffix when naming your header files (unless your project already follows some other convention).<\/p>\n<p>This is a longstanding convention for C++ header files, and most IDEs still default to .h over other options.\n<\/p><\/div>\n<p>Header files are often paired with code files, with the header file providing forward declarations for the corresponding code file.  Since our header file will contain a forward declaration for functions defined in <em>add.cpp<\/em>, we&#8217;ll call our new header file <em>add.h<\/em>.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>If a header file is paired with a code file (e.g. add.h with add.cpp), they should both have the same base name (add).\n<\/p><\/div>\n<p>Here&#8217;s our completed header file:<\/p>\n<p>add.h:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">\/\/ We really should have a header guard here, but will omit it for simplicity (we'll cover header guards in the next lesson)\r\n\r\n\/\/ This is the content of the .h file, which is where the declarations go\r\nint add(int x, int y); \/\/ function prototype for add.h -- don't forget the semicolon!<\/code><\/pre>\n<p>In order to use this header file in main.cpp, we have to #include it (using quotes, not angle brackets).<\/p>\n<p>main.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"add.h\" \/\/ Insert contents of add.h at this point.  Note use of double quotes here.\r\n#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; \"The sum of 3 and 4 is \" &lt;&lt; add(3, 4) &lt;&lt; '\\n';\r\n    return 0;\r\n}<\/code><\/pre>\n<p>add.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"add.h\" \/\/ Insert contents of add.h at this point.  Note use of double quotes here.\r\n\r\nint add(int x, int y)\r\n{\r\n    return x + y;\r\n}<\/code><\/pre>\n<p>When the preprocessor processes the <code>#include \"add.h\"<\/code> line, it copies the contents of add.h into the current file at that point.  Because our <em>add.h<\/em> contains a forward declaration for function <em>add()<\/em>, that forward declaration will be copied into <em>main.cpp<\/em>.  The end result is a program that is functionally the same as the one where we manually added the forward declaration at the top of <em>main.cpp<\/em>.<\/p>\n<p>Consequently, our program will compile and link correctly.<\/p>\n<p><img src=\"https:\/\/2.zoppoz.workers.dev:443\/http\/www.learncpp.com\/images\/CppTutorial\/Section1\/IncludeHeader.png\"><\/p>\n<p>Note: In the graphic above, &#8220;Standard Runtime Library&#8221; should be labelled as the &#8220;C++ Standard Library&#8221;.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">How including definitions in a header file results in a violation of the one-definition rule<\/p>\n<p>For now, you should avoid putting function or variable definitions in header files.  Doing so will generally result in a violation of the one-definition rule (ODR) in cases where the header file is included into more than one source file.<\/p>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Related content<\/p>\n<p>We covered the one-definition rule (ODR) in lesson <a href=\"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/forward-declarations\/\">2.7 -- Forward declarations and definitions<\/a>.\n<\/p><\/div>\n<p>Let&#8217;s illustrate how this happens:<\/p>\n<p>add.h:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">\/\/ We really should have a header guard here, but will omit it for simplicity (we'll cover header guards in the next lesson)\r\n\r\n\/\/ definition for add() in header file -- don't do this!\r\nint add(int x, int y)\r\n{\r\n    return x + y;\r\n}<\/code><\/pre>\n<p>main.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"add.h\" \/\/ Contents of add.h copied here\r\n#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; \"The sum of 3 and 4 is \" &lt;&lt; add(3, 4) &lt;&lt; '\\n';\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>add.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"add.h\" \/\/ Contents of add.h copied here<\/code><\/pre>\n<p>When <code>main.cpp<\/code> is compiled, the <code>#include \"add.h\"<\/code> will be replaced with the contents of <code>add.h<\/code> and then compiled.  Therefore, the compiler will compile something that looks like this:<\/p>\n<p>main.cpp (after preprocessing):<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">\/\/ from add.h:\r\nint add(int x, int y)\r\n{\r\n    return x + y;\r\n}\r\n\r\n\/\/ contents of iostream header here\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; \"The sum of 3 and 4 is \" &lt;&lt; add(3, 4) &lt;&lt; '\\n';\r\n\r\n    return 0;\r\n}<\/code><\/pre>\n<p>This will compile just fine.<\/p>\n<p>When the compiler compiles <code>add.cpp<\/code>, the <code>#include \"add.h\"<\/code> will be replaced with the contents of <code>add.h<\/code> and then compiled.  Therefore, the compiler will compile something like this:<\/p>\n<p>add.cpp (after preprocessing):<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">int add(int x, int y)\r\n{\r\n    return x + y;\r\n}<\/code><\/pre>\n<p>This will also compile just fine.<\/p>\n<p>Finally, the linker will run.  And the linker will see that there are now two definitions for function <code>add()<\/code>: one in main.cpp, and one in add.cpp.  This is a violation of ODR part 2, which states, &#8220;Within a given program, a variable or normal function can only have one definition.&#8221;<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Do not put function and variable definitions in your header files (for now).<\/p>\n<p>Defining either of these in a header file will likely result in a violation of the one-definition rule (ODR) if that header is then #included into more than one source (.cpp) file.\n<\/p><\/div>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Author&#8217;s note<\/p>\n<p>In future lessons, we will encounter additional kinds of definitions that can be safely defined in header files (because they are exempt from the ODR).  This includes definitions for inline functions, inline variables, types, and templates.  We&#8217;ll discuss this further when we introduce each of these.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><a name=\"corresponding_include\"><\/a>Source files should include their paired header <a href=\"#corresponding_include\"><i class=\"fa fa-link\" style=\"font-size: 0.8em;\"><\/i><\/a><\/p>\n<p>In C++, it is a best practice for code files to #include their paired header file (if one exists).  This allows the compiler to catch certain kinds of errors at compile time instead of link time.  For example:<\/p>\n<p>add.h:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">\/\/ We really should have a header guard here, but will omit it for simplicity (we'll cover header guards in the next lesson)\r\n\r\nint add(int x, int y);<\/code><\/pre>\n<p>main.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"add.h\"\r\n#include &lt;iostream&gt;\r\n\r\nint main()\r\n{\r\n    std::cout &lt;&lt; \"The sum of 3 and 4 is \" &lt;&lt; add(3, 4) &lt;&lt; '\\n';\r\n    return 0;\r\n}<\/code><\/pre>\n<p>add.cpp:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"add.h\"         \/\/ copies forward declaration from add.h here\r\n\r\ndouble add(int x, int y) \/\/ oops, return type is double instead of int\r\n{\r\n    return x + y;\r\n}<\/code><\/pre>\n<p>When <em>add.cpp<\/em> is compiled, the forward declaration <code>int add(int x, int y)<\/code> will be copied into <em>add.cpp<\/em> at the point of the #include.  When the compiler reaches the definition <code>double add(int x, int y)<\/code>, it will note that the return types of the forward declaration and the definition don&#8217;t match.  Because functions can&#8217;t differ by only a return type, the compiler will error and abort compilation immediately.  In a larger project, this can save a lot of time and help pinpoint where the issue is.<\/p>\n<div class=\"cpp-note cpp-lightgraybackground\">\n<p class=\"cpp-note-title cpp-bottomline\">As an aside&#8230;<\/p>\n<p>Unfortunately, this doesn&#8217;t work if it is a parameter with a different type instead of a return type.  This is because C++ supports overloaded functions (functions with the same name but different parameter types), so the compiler will assume a function with a mismatched parameter type is a different overload.  Can&#8217;t win em all.\n<\/p><\/div>\n<p>If the <code>#include \"add.h\"<\/code> is not present, the compiler won&#8217;t catch the issue because it doesn&#8217;t see the mismatch.  We have to wait until link time for the issue to surface.<\/p>\n<p>We will also see many examples in future lessons where content required by the source file is defined in the paired header.  In such cases, including the header is a necessity.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Source files should #include their paired header file (if one exists).\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><a name=\"includecpp\"><\/a>Do not #include .cpp files <a href=\"#includecpp\"><i class=\"fa fa-link\" style=\"font-size: 0.8em;\"><\/i><\/a><\/p>\n<p>Although the preprocessor will happily do so, you should generally not <code>#include<\/code> .cpp files.  These should be added to your project and compiled.<\/p>\n<p>There are number of reasons for this:<\/p>\n<ul>\n<li>Doing so can cause naming collisions between source files.\n<\/li>\n<li>In a large project it can be hard to avoid one definition rules (ODR) issues.\n<\/li>\n<li>Any change to such a .cpp file will cause both the .cpp file and any other .cpp file that includes it to recompile, which can take a long time.  Headers tend to change less often than source files.\n<\/li>\n<li>It is non-conventional to do so.\n<\/li>\n<\/ul>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Avoid #including .cpp files.\n<\/p><\/div>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Tip<\/p>\n<p>If your project doesn&#8217;t compile unless you #include .cpp files, that means those .cpp files are not being compiled as part of your project.  Add them to your project or command line so they get compiled.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Troubleshooting<\/p>\n<p>If you get a compiler error indicating that <em>add.h<\/em> isn&#8217;t found, make sure the file is really named <em>add.h<\/em>.  Depending on how you created and named it, it&#8217;s possible the file could have been named something like <em>add<\/em> (no extension) or <em>add.h.txt<\/em> or <em>add.hpp<\/em>.  Also make sure it&#8217;s sitting in the same directory as the rest of your code files.<\/p>\n<p>If you get a linker error about function <em>add<\/em> not being defined, make sure you&#8217;ve included <em>add.cpp<\/em> in your project so the definition for function <em>add<\/em> can be linked into the program.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><a name=\"includemethod\"><\/a>Angled brackets vs double quotes <a href=\"#includemethod\"><i class=\"fa fa-link\" style=\"font-size: 0.8em;\"><\/i><\/a><\/p>\n<p>You&#8217;re probably curious why we use angled brackets for <code>iostream<\/code>, and double quotes for <code>add.h<\/code>.  It&#8217;s possible that a header file with the same filename might exist in multiple directories.  Our use of angled brackets vs double quotes helps give the preprocessor a clue as to where it should look for header files.<\/p>\n<p>When we use angled brackets, we&#8217;re telling the preprocessor that this is a header file we didn&#8217;t write ourselves.  The preprocessor will search for the header only in the directories specified by the <code>include directories<\/code>.  The <code>include directories<\/code> are configured as part of your project\/IDE settings\/compiler settings, and typically default to the directories containing the header files that come with your compiler and\/or OS.  The preprocessor will not search for the header file in your project&#8217;s source code directory.<\/p>\n<p>When we use double-quotes, we&#8217;re telling the preprocessor that this is a header file that we wrote.  The preprocessor will first search for the header file in the current directory.  If it can&#8217;t find a matching header there, it will then search the <code>include directories<\/code>.<\/p>\n<div class=\"cpp-note cpp-lightpurplebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Rule<\/p>\n<p>Use double quotes to include header files that you&#8217;ve written or are expected to be found in the current directory.  Use angled brackets to include headers that come with your compiler, OS, or third-party libraries you&#8217;ve installed elsewhere on your system.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Why doesn&#8217;t iostream have a .h extension?<\/p>\n<p>Another commonly asked question is &#8220;why doesn&#8217;t iostream (or any of the other standard library header files) have a .h extension?&#8221;.  The answer is that <em>iostream.h<\/em> is a different header file than <em>iostream<\/em>!  To explain requires a short history lesson.<\/p>\n<p>When C++ was first created, all of the headers in the standard library ended in a <em>.h<\/em> suffix.  These headers included:<\/p>\n<div class=\"cpp-table-wrapper\">\n<table class=\"cpp-table\">\n<tr>\n<th> Header type <\/th>\n<th> Naming convention <\/th>\n<th> Example <\/th>\n<th> Identifiers placed in namespace <\/th>\n<\/tr>\n<tr>\n<td> C++ specific    <\/td>\n<td> &lt;xxx.h&gt; <\/td>\n<td> iostream.h <\/td>\n<td> Global namespace <\/td>\n<\/tr>\n<tr>\n<td> C compatibility <\/td>\n<td> &lt;xxx.h&gt; <\/td>\n<td> stddef.h   <\/td>\n<td> Global namespace <\/td>\n<\/tr>\n<\/table>\n<\/div>\n<p>The original versions of <em>cout<\/em> and <em>cin<\/em> were declared in <em>iostream.h<\/em> in the global namespace.  Life was consistent, and it was good.  <\/p>\n<p>When the language was standardized by the ANSI committee, they decided to move all of the names used in the standard library into the <em>std<\/em> namespace to help avoid naming conflicts with user-declared identifiers.  However, this presented a problem: if they moved all the names into the <em>std<\/em> namespace, none of the old programs (that included iostream.h) would work anymore!<\/p>\n<p>To work around this issue, C++ introduced new header files that lack the <em>.h<\/em> extension.  These new header files declare all names inside the <em>std<\/em> namespace.  This way, older programs that include <code>#include &lt;iostream.h&gt;<\/code> do not need to be rewritten, and newer programs can <code>#include &lt;iostream&gt;<\/code>.<\/p>\n<p>Modern C++ now contains 4 sets of header files:<\/p>\n<div class=\"cpp-table-wrapper\">\n<table class=\"cpp-table\">\n<tr>\n<th> Header type <\/th>\n<th> Naming convention <\/th>\n<th> Example <\/th>\n<th> Identifiers placed in namespace <\/th>\n<\/tr>\n<tr>\n<td> C++ specific (new)    <\/td>\n<td> &lt;xxx&gt;   <\/td>\n<td> iostream   <\/td>\n<td> <code>std<\/code> namespace <\/td>\n<\/tr>\n<tr>\n<td> C compatibility (new) <\/td>\n<td> &lt;cxxx&gt;  <\/td>\n<td> cstddef    <\/td>\n<td> <code>std<\/code> namespace (required)<br \/>global namespace (optional) <\/td>\n<\/tr>\n<tr>\n<td> C++ specific (old)    <\/td>\n<td> &lt;xxx.h&gt; <\/td>\n<td> iostream.h <\/td>\n<td> Global namespace <\/td>\n<\/tr>\n<tr>\n<td> C compatibility (old) <\/td>\n<td> &lt;xxx.h&gt; <\/td>\n<td> stddef.h   <\/td>\n<td> Global namespace (required)<br \/><code>std<\/code> namespace (optional) <\/td>\n<\/tr>\n<\/table>\n<\/div>\n<div class=\"cpp-note cpp-lightredbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Warning<\/p>\n<p>The new C compatibility headers &lt;cxxx&gt; may optionally declare names in the global namespace, and the old C compatibility headers &lt;xxx.h> may optionally declare names in the <code>std<\/code> namespace.  Names in these locations should be avoided, as those names may not be declared in those locations on other implementations.\n<\/div>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Use the standard library header files without the .h extension.  User-defined headers should still use a .h extension.\n<\/p><\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Including header files from other directories<\/p>\n<p>Another common question involves how to include header files from other directories.<\/p>\n<p>One (bad) way to do this is to include a relative path to the header file you want to include as part of the #include line.  For example:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include \"headers\/myHeader.h\"\r\n#include \"..\/moreHeaders\/myOtherHeader.h\"<\/code><\/pre>\n<p>While this will compile (assuming the files exist in those relative directories), the downside of this approach is that it requires you to reflect your directory structure in your code.  If you ever update your directory structure, your code won&#8217;t work anymore.<\/p>\n<p>A better method is to tell your compiler or IDE that you have a bunch of header files in some other location, so that it will look there when it can&#8217;t find them in the current directory.  This can generally be done by setting an <em>include path<\/em> or <em>search directory<\/em> in your IDE project settings.<\/p>\n<div class=\"cpp-note cpp-lightyellowbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For Visual Studio users<\/p>\n<p>Right click on your project in the <em>Solution Explorer<\/em>, and choose <em>Properties<\/em>, then the <em>VC++ Directories<\/em> tab.  From here, you will see a line called <em>Include Directories<\/em>.  Add the directories you&#8217;d like the compiler to search for additional headers there.\n<\/div>\n<div class=\"cpp-note cpp-lightyellowbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For Code::Blocks users<\/p>\n<p>In Code::Blocks, go to the <em>Project<\/em> menu and select <em>Build Options<\/em>, then the <em>Search directories<\/em> tab.  Add the directories you&#8217;d like the compiler to search for additional headers there.\n<\/div>\n<div class=\"cpp-note cpp-lightyellowbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For gcc users<\/p>\n<p>Using g++, you can use the -I option to specify an alternate include directory:<br \/>\n<code>g++ -o main -I.\/source\/includes main.cpp<\/code><\/p>\n<p>There is no space after the <code>-I<\/code>.  For a full path (rather than a relative path), remove the <code>.<\/code> after <code>-I<\/code>.\n<\/div>\n<div class=\"cpp-note cpp-lightyellowbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">For VS Code users<\/p>\n<p>In your <em>tasks.json<\/em> configuration file, add a new line in the <em>&#8220;Args&#8221;<\/em> section:<br \/>\n<code>\"-I.\/source\/includes\",<\/code><\/p>\n<p>There is no space after the <code>-I<\/code>.  For a full path (rather than a relative path), remove the <code>.<\/code> after <code>-I<\/code>.\n<\/div>\n<p>The nice thing about this approach is that if you ever change your directory structure, you only have to change a single compiler or IDE setting instead of every code file.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Headers may include other headers<\/p>\n<p>It&#8217;s common that the content of a header file will make use of something that is declared (or defined) in another header file.  When this happens, the header file should #include the other header file containing the declaration (or definition) that it needs.<\/p>\n<p>Foo.h:<\/p>\n<pre class=\"language-cpp line-numbers\"><code class=\"language-cpp match-braces\">#include &lt;string_view&gt; \/\/ required to use std::string_view\r\n\r\nstd::string_view getApplicationName(); \/\/ std::string_view used here<\/code><\/pre>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\"><a name=\"transitive\"><\/a>Transitive includes <a href=\"#transitive\"><i class=\"fa fa-link\" style=\"font-size: 0.8em;\"><\/i><\/a><\/p>\n<p>When your source (.cpp) file #includes a header file, you&#8217;ll also get any other header files that are #included by that header (and any header files those include, and so on).  These additional header files are sometimes called <strong>transitive includes<\/strong>, as they&#8217;re included implicitly rather than explicitly.  <\/p>\n<p>The content of these transitive includes are available for use in your code file.  However, you generally should not rely on the content of headers that are included transitively (unless reference documentation indicates that those transitive includes are required).  The implementation of header files may change over time, or be different across different systems.  If that happens, your code may only compile on certain systems, or may compile now but not in the future.  This is easily avoided by explicitly including all of the header files the content of your code file requires.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>Each file should explicitly #include all of the header files it needs to compile.  Do not rely on headers included transitively from other headers.\n<\/p><\/div>\n<p>Unfortunately, there is no easy way to detect when your code file is accidentally relying on content of a header file that has been included by another header file.<\/p>\n<div class=\"cpp-note cpp-lightbluebackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Q: I didn&#8217;t include &lt;someheader&gt; and my program worked anyway! Why?<\/p>\n<div id=\"missing_include_but_works\"><\/div>\n<p>This is one of the most commonly asked questions on this site.  The answer is: it&#8217;s likely working, because you included some other header (e.g. &lt;iostream&gt;), which itself included &lt;someheader&gt;.  Although your program will compile, per the best practice above, you should not rely on this.  What compiles for you might not compile on a friend&#8217;s machine.<\/p>\n<\/div>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">The order of inclusion for header files<\/p>\n<p>If your header files are written properly and #include everything they need, the order of inclusion shouldn&#8217;t matter.<\/p>\n<p>Now consider the following scenario: let&#8217;s say header A needs declarations from header B, but forgets to include it.  In our code file, if we include header B before header A, our code will still compile!  This is because the compiler will compile all the declarations from B before it compiles the code from A that depends on those declarations.<\/p>\n<p>However, if we include header A first, then the compiler will complain because the code from A will be compiled before the compiler has seen the declarations from B.  This is actually preferable, because the error has been surfaced, and we can then fix it.<\/p>\n<div class=\"cpp-note cpp-lightgreenbackground\">\n<p class=\"cpp-note-title cpp-bottomline\">Best practice<\/p>\n<p>To maximize the chance that missing includes will be flagged by compiler, order your #includes as follows (skipping any that are not relevant):<\/p>\n<ul>\n<li>The paired header file for this code file (e.g. <code>add.cpp<\/code> should <code>#include \"add.h\"<\/code>)\n<\/li>\n<li>Other headers from the same project (e.g. <code>#include \"mymath.h\"<\/code>)\n<\/li>\n<li>3rd party library headers (e.g. <code>#include &lt;boost\/tuple\/tuple.hpp&gt;<\/code>)\n<\/li>\n<li>Standard library headers (e.g. <code>#include &lt;iostream&gt;<\/code>)\n<\/li>\n<\/ul>\n<p>The headers for each grouping should be sorted alphabetically (unless the documentation for a 3rd party library instructs you to do otherwise).\n<\/p><\/div>\n<p>That way, if one of your user-defined headers is missing an #include for a 3rd party library or standard library header, it&#8217;s more likely to cause a compile error so you can fix it.<\/p>\n<p class=\"cpp-section cpp-topline\" style=\"clear: both\">Header file best practices<\/p>\n<p>Here are a few more recommendations for creating and using header files.<\/p>\n<ul>\n<li>Always include header guards (we&#8217;ll cover these next lesson).\n<\/li>\n<li>Do not define variables and functions in header files (for now).\n<\/li>\n<li>Give a header file the same name as the source file it&#8217;s associated with (e.g. <code>grades.h<\/code> is paired with <code>grades.cpp<\/code>).\n<\/li>\n<li>Each header file should have a specific job, and be as independent as possible.  For example, you might put all your declarations related to functionality A in A.h and all your declarations related to functionality B in B.h.  That way if you only care about A later, you can just include A.h and not get any of the stuff related to B.\n<\/li>\n<li>Be mindful of which headers you need to explicitly include for the functionality that you are using in your code files, to avoid inadvertent transitive includes.\n<\/li>\n<li>A header file should #include any other headers containing functionality it needs.  Such a header should compile successfully when #included into a .cpp file by itself.\n<\/li>\n<li>Only #include what you need (don&#8217;t include everything just because you can).\n<\/li>\n<li>Do not #include .cpp files.\n<\/li>\n<li>Prefer putting documentation on what something does or how to use it in the header.  It&#8217;s more likely to be seen there.  Documentation describing how something works should remain in the source files.\n<\/li>\n<\/ul>\n<div class=\"prevnext\"><div class=\"prevnext-inline\">\n\t<a class=\"nav-link\" href=\"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/header-guards\/\">\n <div class=\"nav-button nav-button-next\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-right\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Next lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">2.12<\/span>Header guards\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  \t<a class=\"nav-link\" href=\"\/https\/www.learncpp.com\/\">\n  <div class=\"nav-button nav-button-index\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-home\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Back to table of contents<\/div>\n    <\/div>\n<\/div><\/a>\n  \t<a class=\"nav-link\" href=\"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/cpp-tutorial\/introduction-to-the-preprocessor\/\">\n  <div class=\"nav-button nav-button-prev\">\n    <div class=\"nav-button-icon\"><i class=\"fa fa-chevron-circle-left\" aria-hidden=\"true\"><\/i><\/div>\n    <div class=\"nav-button-text\">\n      <div class=\"nav-button-title\">Previous lesson<\/div>\n      <div class=\"nav-button-lesson\">\n        <span class=\"nav-button-lesson-number\">2.10<\/span>Introduction to the preprocessor\n      <\/div>\n    <\/div>\n  <\/div><\/a>\n  <\/div><\/div>\n","protected":false},"excerpt":{"rendered":"<p>In lesson , we discussed how programs can be split across multiple files. We also discussed how forward declarations are used to allow the code in one file to access something defined in another file. When programs contain only a few small files, manually adding a few forward declarations to &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[3],"tags":[],"_links":{"self":[{"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/32"}],"collection":[{"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/comments?post=32"}],"version-history":[{"count":134,"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/32\/revisions"}],"predecessor-version":[{"id":18230,"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/posts\/32\/revisions\/18230"}],"wp:attachment":[{"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/media?parent=32"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/categories?post=32"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/2.zoppoz.workers.dev:443\/https\/www.learncpp.com\/wp-json\/wp\/v2\/tags?post=32"}],"curies":[{"name":"wp","href":"https:\/\/2.zoppoz.workers.dev:443\/https\/api.w.org\/{rel}","templated":true}]}}