If I have a static local variable or thread_local local variable that is within an inline function that is defined in different translation units, in the final program are they guaranteed by the standard to have the same address?
// TU1:
inline int* f() { static int x; return &x; }
extern int* a;
void sa() { a = f(); }
// TU2:
inline int* f() { static int x; return &x; }
extern int* b;
void sb() { b = f(); }
// TU3:
int *a, *b;
void sa();
void sb();
int main() { sa(); sb(); return a == b; }
Will the above always return 1?
Static local variables are not allowed to be defined within the body of an inline function. C++ functions implemented inside of a class declaration are automatically defined inline.
In C99, an inline or extern inline function must not access static global variables or define non- const static local variables. const static local variables may or may not be different objects in different translation units, depending on whether the function was inlined or whether a call was made.
In C++ (before C++17 version), we cannot initialize the value of static variables directly in the class. We have to define them outside of the class.
A variable declared inline has the same semantics as a function declared inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is used, and the behavior of the program is as if there was exactly one variable.
Yes, it's always the same object. By [dcl.fct.spec]/4:
An
inline
function with external linkage shall have the same address in all translation units. Astatic
local variable in anextern inline
function always refers to the same object. A type defined within the body of anextern inline
function is the same type in every translation unit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With