Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No linker error when global variable declared static in the header file [duplicate]

Possible Duplicate:
Static variables in C++

// x.h
int i = 3;

// x1.cpp
#include"x.h"
//...

// x2.cpp
#include"x.h"
//...

Above code will give linker error. However If I declare,

//x.h
static int i = 3;

It doesn't give linker error in gcc, even we have the same #include! Are we creating different static int i; for every .cpp file ? Will it cause any silent linking bug (due to same name)?

like image 579
iammilind Avatar asked Feb 21 '26 10:02

iammilind


1 Answers

When C code is compiled, it's one "translation unit" at a time. Early on, #includes are expanded into the text of the referenced files. So what you've got in the static case is equivalent to x1.cpp saying static int i = 3; and x2.cpp doing the same. And static in this context means roughly "don't share this with other translation units."

So yes, when you use static there you are making two different i variables which have nothing to do with each other. This will not cause a linking error.

like image 90
John Zwinck Avatar answered Feb 24 '26 00:02

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!