Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>yes, but you are only declaring it once <strong>per compilation unit</strong>.</p> <p>include guards only make sure you declare things once per .cpp that uses it.</p> <p>So if <code>A.h</code> is included in <code>B.h</code> and <code>impl.cpp</code> includes both, then <code>A.h</code> is included only the first time.</p> <p>In your case, you are defining the value of the include guard macro as a static pointer variable. So even if <code>impl.cpp</code> has it only once, <code>impl2.cpp</code> which includes the same files will have them as well, so your static variable will have duplicate definitions at link-time</p> <p>if you insist in having static variables (as Thomas said, it is usually bad design) it is better to wrap them in a function;</p> <pre><code>myClass* getInstance() { static myClass instance; return &amp;instance; } </code></pre> <p>this is slightly better because it makes sure the variable is truly global, some architectures (like darwin) have that <code>static</code> variables are unique per dynamic library, not per process, so it might led to confusing behavior/portability</p> <p>Also, and more relevant, static initialization always happens before main, and the order is not guaranteed. With static function variables, the variables are initialised "on demand" and so it is not affected by initialization ordering issues</p> <p>to initialise a global pointer:</p> <pre><code> myClass** getGlobalRef() { static myClass* val; return &amp;val; } //and you set it at run-time, avoiding static-initialization happening before main * getGlobalRef() = new myClass(); </code></pre>
 

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