-1

B.cpp

 #include <iostream>
 static int x=4;   
 void print_x()  {  std::cout<< x;  }

A.cpp

 #include <iostream>
void print_x();  //forward declaration 
int x=3;
int main ()
{
std::cout<< x << "    ";
print_x();
} 
// output 3     4

i run this code in visual studio 2019 and i got this output but i expected found link error because when function get_x() excuted the linker will see two definitions first one is static x in B.cpp and second one is x in A.cpp because it's have externel linkage
so why this code is run correctly?

Abdo Mostafa
  • 65
  • 1
  • 4
  • `get_x` or `print_x`? – KamilCuk Aug 18 '20 at 05:49
  • sorry , i edit it – Abdo Mostafa Aug 18 '20 at 07:02
  • Because `print_x` is implemented to use variable `x` in the B translation unit. It doesn't matter that your local variable `x` in main has the same name, because for the compiler they are different things. Run `objdump -d` on your executable and compare assembly of `cout << x` in main and `cout << x` in `print_x`, you will see that different variables are loaded. – pptaszni Aug 18 '20 at 07:39

1 Answers1

0

The static variable is not shared with other translation unit (internal linkage), thus this is a different variable from the global one defined in A.cpp.

For the linker, ODR constraint is maintained. This post might help you as well.

cigien
  • 57,834
  • 11
  • 73
  • 112
nop666
  • 585
  • 2
  • 6