質問

Why when we redefined variable in the other modules it's ok to linking this modules together? I've written two modules main.cpp and module.cpp as the following:

//--main.cpp--//
#include <stdio.h>

int main(){
    int i=5;
    printf("The value of i is %d",i);
}

and the

//--module.cpp--//
int i=7;

Now I'm compiling and linking their with g++ as the following:

g++ -c main.cpp
g++ -c module.coo
g++ -o bin main.o module.o

And it's ok. But I'm expected that the compilation will be successful only whereas linker will throw an exception like redefining varaible. When I'm running ./bin output is The value of i is 5.

UPD: I'm understand that if we declare i as global variable of module main.cpp that linker will throw an error.

役に立ちましたか?

解決

In function main variable i is a local variable of the function. It is not visible and exists outside the function.

Consider the following example

#include <iostream>

int i = 3;

int main()
{
   int i = 10

   std::cout << "i = " << i << std::endl;
   std::cout << "::i = " << ::i << std::endl;

   i = ::i;

   std::cout << "i = " << i << std::endl;
   std::cout << "::i = " << ::i << std::endl;

   {
        int i = 20;

        std::cout << "i = " << i << std::endl;
        std::cout << "::i = " << ::i << std::endl;
   }

   std::cout << "i = " << i << std::endl;
   std::cout << "::i = " << ::i << std::endl;
}

Local variables have no linkage.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top