Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You seem to have them mixed up.</p> <p>You are right about </p> <pre><code>static const std::string Ten = "10"; </code></pre> <p>version. It will "work", but it will create a separate object in each translation unit. </p> <p>The version without <code>static</code> will have the same effect. It <em>won't</em> produce linker errors, but will define a separate object in each translation unit. In C++ language <code>const</code> objects have internal linkage by default, meaning that</p> <pre><code>const std::string Ten = "10"; // `static` is optional </code></pre> <p>is exactly equivalent to the previous version with <code>static</code>.</p> <p>The version with <code>extern</code> and initializer </p> <pre><code>extern const std::string Ten = "10"; // it's a definition! </code></pre> <p>will produce a <em>definition</em> of an object with external linkage (it is a definition because of the presence of an initializer). <em>This</em> version will result in linker errors, since you'll end up with multiple definitions of an object with external linkage - a violation of ODR.</p> <h3>Here's how you can do it:</h3> <p>In order to achieve what you are trying to achieve, you have to <em>declare</em> your constant in the header file</p> <pre><code>extern const std::string Ten; // non-defining declaration </code></pre> <p>and then define it (with initializer) in one and only one of the implementation files</p> <pre><code>extern const std::string Ten = "10"; // definition, `extern` optional </code></pre> <p>(If the constant is pre-declared as <code>extern</code>, then <code>extern</code> in the definition is optional. Even without an explicit <code>extern</code> it will define a const object with external linkage.)</p>
 

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