Note that there are some explanatory texts on larger screens.

plurals
  1. POConst static variable defined in header file has same address in different translation unit
    primarykey
    data
    text
    <p>I have checked out the definition of std::ios::app in /usr/include/c++/4.6/bits/ios_base.h and found that std::ios::app is defined as a const static variable: </p> <pre><code>typedef _Ios_Openmode openmode; /// Seek to end before each write. static const openmode app = _S_app; </code></pre> <p>in which _Ios_Openmode is defined in the same header file as </p> <pre><code>enum _Ios_Openmode { _S_app = 1L &lt;&lt; 0, _S_ate = 1L &lt;&lt; 1, _S_bin = 1L &lt;&lt; 2, _S_in = 1L &lt;&lt; 3, _S_out = 1L &lt;&lt; 4, _S_trunc = 1L &lt;&lt; 5, _S_ios_openmode_end = 1L &lt;&lt; 16 }; </code></pre> <p>It's well known that static variable has internal linkage and every translation unit has its own copy of this static variable, which means static variables in different translation unit should have different addresses. However, I have used two separate programs to print address of std::ios::app and found that the printed address are the same:</p> <p>source file test1.cpp</p> <pre><code>#include &lt;iostream&gt; int main() { std::cout &lt;&lt; "address: " &lt;&lt; &amp;std::ios::app &lt;&lt; std::endl; return 0; } </code></pre> <p>result</p> <pre><code>address: 0x804a0cc </code></pre> <p>source file test2.cpp is the same with test1.cpp and the result is the same:</p> <pre><code>address: 0x804a0cc </code></pre> <p>This really confused me, shouldn't static variables in different translation units have different addresses?</p> <hr> <p>Update: as is pointed out in the comments, std::ios::app is a static data member rather than a static const variable; static data member has external linkage and addresses of static data member in different translation unit should be the same. The second point is that my method for validating this fact is wrong: different program does not mean different translation unit. </p>
    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.
 

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