Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h1>Separate compilation in a nutshell</h1> <p>First, let's get some quick examples out there:</p> <pre><code>struct ClassDeclaration; // 'class' / 'struct' mean almost the same thing here struct ClassDefinition {}; // the only difference is default accessibility // of bases and members void function_declaration(); void function_definition() {} extern int global_object_declaration; int global_object_definition; template&lt;class T&gt; // cannot replace this 'class' with 'struct' struct ClassTemplateDeclaration; template&lt;class T&gt; struct ClassTemplateDefinition {}; template&lt;class T&gt; void function_template_declaration(); template&lt;class T&gt; void function_template_definition() {} </code></pre> <h3><strong>Translation Unit</strong></h3> <p>A <em>translation unit</em> (TU) is a single source file (should be a **.cpp* file) and all the files it includes, and they include, etc. In other words: the result of preprocessing a single file.</p> <h3><strong>Headers</strong></h3> <p>Include guards are a hack to work around lack of a real module system, making headers into a kind of limited module; to this end, including the same header more than once must not have an adverse affect.</p> <p>Include guards work by making subsequent #includes no-ops, with the definitions available from the first include. Because of their limited nature, macros which control header options should be consistent throughout a project (oddball headers like &lt;assert.h&gt; cause problems) and all #includes of public headers should be outside of any namespace, class, etc., usually at the top of any file.</p> <p>See my include guard <a href="https://stackoverflow.com/questions/1744144/adding-ifndef-define-endif-breaks-the-compile/1744302#1744302">naming advice</a>, including a short program to <a href="http://bitbucket.org/kniht/scraps/src/tip/python/includeguard.py" rel="nofollow noreferrer">generate include guards</a>.</p> <h3><strong>Declarations</strong></h3> <p><em>Classes</em>, <em>functions</em>, <em>objects</em>, and <em>templates</em> may be declared almost anywhere, may be declared any number of times, and <em>must</em> be declared before referring to them in any way. In a few weird cases, you can declare classes as you use them; won't cover that here.</p> <h3><strong>Definitions</strong></h3> <p><em>Classes</em> may be defined at most once<sup>[1]</sup> per TU; this typically happens when you include a header for a particular class. <em>Functions</em> and <em>objects</em> must be defined once in exactly one TU; this typically happens when you implement them in a **.cpp* file. However, <em>inline functions</em>, including implicitly inline functions inside class definitions, may be defined in multiple TUs, but the definitions must be identical.</p> <p>For practical purposes<sup>[2]</sup>, <em>templates</em> (both class templates and function templates) are defined only in headers, and if you want to use a separate file, then use another header<sup>[3]</sup>.</p> <p><sup>[1]</sup> Because of the at-most-once restriction, headers use include guards to prevent multiple inclusion and thus multiple definition errors.<br> <sup>[2]</sup> I won't cover the other possibilities here.<br> <sup>[3]</sup> Name it <em>blahblah_detail.hpp</em>, <em>blahblah_private.hpp</em>, or similar if you want to document that it's non-public.</p> <h2>Guidelines</h2> <p>So, while I'm sure everything above is all a big ball of mud so far, it's less than a page on what should take up a few chapters, so use it as a brief reference. Understanding the concepts above, however, is important. Using those, here's a short list of guidelines (but not absolute rules):</p> <ul> <li><em>Always</em> name headers consistently in a single project, such as **.h* for C and **.hpp* for C++.</li> <li><em>Never</em> include a file which is not a header.</li> <li><em>Always</em> name implementation files (which are going to be directly compiled) consistently, such as **.c* and **.cpp*.</li> <li>Use a <em>build system</em> which can compile your source files automatically. <em>make</em> is the canonical example, but there are many alternatives. Keep it simple in simple cases. For example, make can be used its built-in rules and even without a makefile.</li> <li>Use a build system which can generate header dependencies. Some compilers can generate this with command-line switches, such as <em>-M</em>, so you can make a <a href="http://bitbucket.org/kniht/scraps/src/tip/cpp/Makefile.common" rel="nofollow noreferrer">surprisingly useful system</a> easily.</li> </ul> <h2>Build Process</h2> <p>(Here's the tiny bit that answers your question, but you need most of the above in order to get here.)</p> <p>When you build, the build system will then go through several steps, of which the important ones for this discussion are:</p> <ol> <li>compile each implementation file as a TU, producing an object file (**.o*, **.obj*) <ul> <li>each is compiled <em>independently</em> of the others, which is why each TU needs declarations and definitions</li> </ul></li> <li>link those files, along with libraries specified, into a single executable</li> </ol> <p>I recommend you learn the rudiments of make, as it is popular, well-understood, and easy to get started with. However, it's an old system with several problems, and you'll want to switch to something else at some point.</p> <p>Choosing a build system is almost a religious experience, like choosing an editor, except you'll have to work with more people (everyone working on the same project) and will likely be much more constrained by precedent and convention. You can use an IDE which handles the same details for you, but this has no real benefit from using a comprehensive build system instead, and you really should still know what it's doing under the hood.</p> <h2>File Templates</h2> <h3>example.hpp</h3> <pre><code>#ifndef EXAMPLE_INCLUDE_GUARD_60497EBE580B4F5292059C8705848F75 #define EXAMPLE_INCLUDE_GUARD_60497EBE580B4F5292059C8705848F75 // all project-specific macros for this project are prefixed "EXAMPLE_" #include &lt;ostream&gt; // required headers/"modules"/libraries from the #include &lt;string&gt; // stdlib, this project, and elsewhere #include &lt;vector&gt; namespace example { // main namespace for this project template&lt;class T&gt; struct TemplateExample { // for practical purposes, just put entire void f() {} // definition of class and all methods in header T data; }; struct FooBar { FooBar(); // declared int size() const { return v.size(); } // defined (&amp; implicitly inline) private: std::vector&lt;TemplateExample&lt;int&gt; &gt; v; }; int main(std::vector&lt;std::string&gt; args); // declared } // example:: #endif </code></pre> <h3>example.cpp</h3> <pre><code>#include "example.hpp" // include the headers "specific to" this implementation // file first, helps make sure the header includes anything it needs (is // independent) #include &lt;algorithm&gt; // anything additional not included by the header #include &lt;iostream&gt; namespace example { FooBar::FooBar() : v(42) {} // define ctor int main(std::vector&lt;std::string&gt; args) { // define function using namespace std; // use inside function scope, if desired, is always okay // but using outside function scope can be problematic cout &lt;&lt; "doing real work now...\n"; // no std:: needed here return 42; } } // example:: </code></pre> <h3>main.cpp</h3> <pre><code>#include &lt;iostream&gt; #include "example.hpp" int main(int argc, char const** argv) try { // do any global initialization before real main return example::main(std::vector&lt;std::string&gt;(argv, argv + argc)); } catch (std::exception&amp; e) { std::cerr &lt;&lt; "[uncaught exception: " &lt;&lt; e.what() &lt;&lt; "]\n"; return 1; // or EXIT_FAILURE, etc. } catch (...) { std::cerr &lt;&lt; "[unknown uncaught exception]\n"; return 1; // or EXIT_FAILURE, etc. } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload