Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ static variable

Tags:

c++

static

I am trying to design header only library, which unfortunately needs to have global static variable (either in class or in namespace).

Is there any way or preferred solution to have global static variable while maintaining header only design?

The code is here

like image 470
Anycorn Avatar asked Sep 19 '10 07:09

Anycorn


People also ask

What is a static variable in C?

In programming, a static variable is the one allocated “statically,” which means its lifetime is throughout the program run. It is declared with the 'static' keyword and persists its value across the function calls.

Are there static variables in C?

Syntax and Use of the Static Variable in COne can define a static variable both- outside or inside the function. These are local to the block, and their default value is always zero. The static variables stay alive till the program gets executed in the end.

Can you change static variable in C?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program.

Does C support static?

Static is a keyword used in C programming language. It can be used with both variables and functions, i.e., we can declare a static variable and static function as well. An ordinary variable is limited to the scope in which it is defined, while the scope of the static variable is throughout the program.


1 Answers

There are a couple of options. The first thing that came to my mind was that C++ allows static data members of class templates to be defined in more than one translation unit:

template<class T>
struct dummy {
   static int my_global;
};

template<class T>
int dummy<T>::my_global;

inline int& my_global() {return dummy<void>::my_global;}

The linker will merge multiple definitions into one. But inline alone is also able to help here and this solution is much simpler:

inline int& my_global() {
   static int g = 24;
   return g;
}

You can put this inline function into a header file and include it into many translation units. C++ guarantees that the reference returned by this inline function will always refer to the same object. Make sure that the function has external linkage.

like image 67
sellibitze Avatar answered Oct 10 '22 08:10

sellibitze