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?

user1000
  • 79
  • 2
  • 9
  • Yes, it's redundant. Both `const` and `static` create internal linkage. – Barmar Jun 09 '18 at 00: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. – Barmar Jun 09 '18 at 00:25
  • Related: https://stackoverflow.com/questions/998425/why-does-const-imply-internal-linkage-in-c-when-it-doesnt-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Barmar Jun 09 '18 at 00:25

1 Answers1

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.

  • 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`. – Barmar Jun 09 '18 at 00:36
  • Yes for global variables static is redundant if you use const. – Sachin Sharma Jun 09 '18 at 00:44
  • In fact, the first line of the question specifically says "If I define global variable as" – Barmar Jun 09 '18 at 00:45
  • 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. – Sachin Sharma Jun 09 '18 at 00:48