Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy c++ puts same-named variables defined in separate modules into same address in memory?
    primarykey
    data
    text
    <p>Let's take header file <code>var.h</code> </p> <pre><code>#include &lt;iostream&gt; class var {public: var () {std::cout &lt;&lt; "Creating var at " &lt;&lt; this &lt;&lt; std::endl; } ~var () {std::cout &lt;&lt; "Deleting var at " &lt;&lt; this &lt;&lt; std::endl; } }; </code></pre> <p>and two source files, first <code>lib.cpp</code></p> <pre><code>#include "var.h" var A; </code></pre> <p>and second <code>app.cpp</code></p> <pre><code>#include "var.h" var A; int main () {return 0; } </code></pre> <p>then, if I attempt to compile them</p> <pre><code>g++ -c app.cpp g++ -c lib.cpp g++ -o app app.o lib.o </code></pre> <p>linker return multiply defined variable error. But, if I compile it onto shared library + main app</p> <pre><code>g++ -fPIC -c lib.cpp g++ --shared -o liblib.so lib.o g++ -fPIC -c app.cpp g++ -o app -llib -L . app.o </code></pre> <p>it links without error. However program doesn't work properly:</p> <pre><code>./app Creating var at 0x6013c0 Creating var at 0x6013c0 Deleting var at 0x6013c0 Deleting var at 0x6013c0 </code></pre> <p>so different variables was created at the same memory address! It might put into serious trouble, for example, in a case when library and application expect them to have different values (values of object fields in this case).</p> <p>if <code>class var</code> do memory allocation/deleting valgrind warns about accessing memory in recently deleted block.</p> <p>Yes, I know I could put <code>static var A;</code> instead of <code>var A;</code> and both ways to compile will work properly. My question is: why one can't use same-named variables (or even functions?) in different libraries? Library creators might know nothing about names each other use and not to be warned to use <code>static</code>. Why GNU linked doesn't warn about this conflict?</p> <p>And, BTW, could <code>dlload</code> put into same trouble?</p> <p>UPD. Thank you all for explaining about namespaces and extern, I see why same symbols are placed into same memory address, but still I can't get why no linking error or even warning about doubly defined variable is shown but wrong code produced in second case.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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