Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If all you want is to define a constant, try this instead:</p> <pre><code>namespace N1 { enum MyEnum { b = 80 }; } </code></pre> <p>Include guards are a good idea for almost any .h file, but they're probably not your problem here. There are two main parts to the all-important <a href="http://en.wikipedia.org/wiki/One_Definition_Rule" rel="nofollow">One Definition Rule</a>: the first says that each symbol may only be defined once per translation unit (which generally means a .cpp file). That's what include guards are for: they prevent a header from being included twice, which would lead to a symbol (like N::b) being defined more than once in the same translation unit (= .cpp file).</p> <p>But this is not all, however. Some symbols, such as classes, non-inline functions, and some variable definitions can only be declared once for <strong>the entire program</strong>. This is not unreasonable: let's suppose you allowed defining an int value called MyInt as 40 in one translation unit and as 80 in another: how the compiler would know which one to use? Of course, you can <strong>declare</strong> such symbols more than once per program (but only once per translation unit) - or they would only be usable in the translation unit they were declared in. But you cannot <strong>define</strong> them in more than one translation unit.</p> <p>Using enum was an easy way to avoid having to separate declaration and definition in your case (since enum isn't subject to the second version of the One Definition Rule), but if you really need a (non-const) global of <code>int</code> type, you could achieve it this way:</p> <p><strong>sample.h</strong></p> <pre><code>namespace N1 { // The extern keyword tells the compiler that this is is only // a declaration and the variable is defined elsewhere. extern int b; } </code></pre> <p><strong>sample1.cpp</strong></p> <pre><code>#include "sample.h" namespace N1 { // This is the definition! int b = 5; } void foo() { using namespace std; cout&lt;&lt;N1:b&lt;&lt;endl; } </code></pre> <p><strong>sample2.cpp</strong></p> <pre><code>#include "sample.h" // No need to define N1::b, since it was already defined in sample1.cpp. void bar() { using namespace std; cout&lt;&lt;N1:b&lt;&lt;endl; } </code></pre>
    singulars
    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. This table or related slice is empty.
    1. 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