1

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?

3
  • Yes, it's redundant. Both const and static create internal linkage. Commented Jun 9, 2018 at 0:24
  • 2
    Note that this is a difference between C++ and C. So if you're writing a header file that could be used in both, you need the redundancy. Commented Jun 9, 2018 at 0:25
  • Related: stackoverflow.com/questions/998425/… Commented Jun 9, 2018 at 0:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

He only seems to be talking about global variables, since those are the only ones that cause the multiple definition error if you leave out static or const.
Yes for global variables static is redundant if you use const.
In fact, the first line of the question specifically says "If I define global variable as"
Yes, i see that but still one must be clear about the diffrences between static and const. I feel static must be used for global variables because in c++ const does not mean constant but it means 'read only'. The value can be changed by using pointers. So i find using const a bit confusing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.