Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local static/thread_local variables of inline functions?

Tags:

c++

c++11

c++14

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?

like image 947
Andrew Tomazos Avatar asked Aug 23 '15 22:08

Andrew Tomazos


People also ask

Can inline functions have static variables?

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.

Should inline functions be static?

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.

Can we use inline static variable inside class?

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.

What are inline variables?

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.


1 Answers

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. A static local variable in an extern inline function always refers to the same object. A type defined within the body of an extern inline function is the same type in every translation unit.

like image 132
Kerrek SB Avatar answered Oct 04 '22 15:10

Kerrek SB