Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The simplest way is to declare it in a header as <code>const static int i=10;</code> and include that header in all the <code>.cpp</code> that need that constant. This will allow it to be "inlined" by the compiler in every object file, still avoiding ODR violations.</p> <p>---edit---</p> <p>Actually, in C++ the <code>static</code> is not required, since <code>const</code> objects have internal linkage by default. But in C, you have to put that <code>static</code> (and in C++ it doesn't hurt).</p> <p>Why is this better than the <code>extern</code> method? Because:</p> <ol> <li>it's more idiomatic. In C++ you'll always write integral constants in headers as <code>const</code> variables (and that's the very reason why they have internal linkage by default).</li> <li>it's less typing. You just have to write the <code>const</code> declaration once, then your constants are just a <code>#include</code> away.</li> <li>it (usually) produces more efficient code. The definition of <code>extern</code>-declared variables cannot be accessed by the compiler when it is producing the current object module, so it cannot optimize it by putting its actual value as an immediate value in the produced machine code, it cannot eliminate branches that cannot be reached with that value of the constant, ... Sure, cross-module optimization ("link time code generation", "whole program optimization", ...) does exist, but at the moment compilers have more advanced optimizers than linkers.</li> </ol>
    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.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    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