summaryrefslogtreecommitdiff
path: root/devdocs/gcc~13/static-definitions.html
blob: e529ff8b8f14fcf24de512da4031515be9d26942 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="subsection-level-extent" id="Static-Definitions"> <div class="nav-panel"> <p> Next: <a href="name-lookup" accesskey="n" rel="next">Name Lookup, Templates, and Accessing Members of Base Classes</a>, Up: <a href="c_002b_002b-misunderstandings" accesskey="u" rel="up">Common Misunderstandings with GNU C++</a> [<a href="index#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="indices" title="Index" rel="index">Index</a>]</p> </div>  <h1 class="subsection" id="Declare-and-Define-Static-Members"><span>14.7.1 Declare <em class="emph">and</em> Define Static Members<a class="copiable-link" href="#Declare-and-Define-Static-Members"> ¶</a></span></h1>     <p>When a class has static data members, it is not enough to <em class="emph">declare</em> the static member; you must also <em class="emph">define</em> it. For example: </p> <div class="example smallexample"> <pre class="example-preformatted" data-language="cpp">class Foo
{
  …
  void method();
  static int bar;
};</pre>
</div> <p>This declaration only establishes that the class <code class="code">Foo</code> has an <code class="code">int</code> named <code class="code">Foo::bar</code>, and a member function named <code class="code">Foo::method</code>. But you still need to define <em class="emph">both</em> <code class="code">method</code> and <code class="code">bar</code> elsewhere. According to the ISO standard, you must supply an initializer in one (and only one) source file, such as: </p> <div class="example smallexample"> <pre class="example-preformatted" data-language="cpp">int Foo::bar = 0;</pre>
</div> <p>Other C++ compilers may not correctly implement the standard behavior. As a result, when you switch to <code class="command">g++</code> from one of these compilers, you may discover that a program that appeared to work correctly in fact does not conform to the standard: <code class="command">g++</code> reports as undefined symbols any static data members that lack definitions. </p> </div><div class="_attribution">
  <p class="_attribution-p">
    &copy; Free Software Foundation<br>Licensed under the GNU Free Documentation License, Version 1.3.<br>
    <a href="https://gcc.gnu.org/onlinedocs/gcc-13.1.0/gcc/Static-Definitions.html" class="_attribution-link">https://gcc.gnu.org/onlinedocs/gcc-13.1.0/gcc/Static-Definitions.html</a>
  </p>
</div>