简体   繁体   中英

Static const vs const in global variable

In Foo.h I define 1 global variable as

static const int g_var = 4;

Then I include this header file in many different header files and .cpp files. If I just write

int g_var = 4;

I get errors "g_var already defined in", which is understandable, so I had to add static so it is just initialized once. But using

const int g_var = 4; 

solves the "already defined in" problem. I read that this is because const global variables have internal linkage by default. So is the keyword static here redundant?

Static keyword is an access specifier. If you use static inside a function it allows the variable to exist outside the function scope and preserve its value between diffrent function calls. If you define a static variable or constant outside a function its scope will be limited to that particular file. With constant, static keyword simply optimizes the complilation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM