cLax
cLax

Reputation: 113

Global variables in a header file

I was just wondering if you declare a variable in a header file like this

const static int START = 0; 

would that variable (START) be considered global?

Upvotes: 0

Views: 79

Answers (2)

JL. Sanchez
JL. Sanchez

Reputation: 371

Yes and no.

Lets say you add that definition into 'myvar.h' and then you include that header file into 'main.c' and 'other.c'

All functions in 'main.c' and 'other.c' will know about the defined variable --so in a way, it is global.

But in fact there will be two different variables with the same name. Changes made by functions in 'main.c' won't be visible by functions in 'other.c' and vice versa.

That's because static variables defined outside of functions are considered 'local to the compilation unit'.

On the other hand, if you just remove the 'static' keyword, the variable will be defined twice (once for each compilation unit in which the header file is included) and the linker will emit a 'duplicate symbol' error.

Upvotes: 0

Acorn
Acorn

Reputation: 26194

If you define:

const static int START = 0;

at file scope, then START will have internal linkage and static duration due to static.

This means that each translation unit that includes the header will end up with a copy of the symbol and that each of them will live throughout the entire program.

Upvotes: 2

Related Questions