Declaring a global variable `extern const int` in the header, but only` int` in the source file

I experimented with GCC and found that you can declare external const variables in header files, but keep them mutable in implementation files.

EDIT . It really doesn't work. The only reason I got my test code for compilation was because I did not include "header.h" in "header.c".

header.h:

 #ifndef HEADER_H_ #define HEADER_H_ extern const int global_variable; #endif 

header.c:

 int global_variable = 17; 

This seems like a very good function for storing global_variable only for header.h users, but saving their modifications through implementation ( header.c ).

NOTE. The following code is just an example of how this declaration method will prevent global_variable from being assigned.

 #include "header.h" int main(void) { global_variable = 34; /* This is an error as `global_variable` is declared const */ return 0; } 

Because I have never seen technology in practice before. I'm starting to wonder if this is true.

Is this the correct behavior or is it a mistake that the GCC cannot warn me about?

+7
c external global-variables header constants
source share
3 answers

const int and int are not compatible types.

For example:

 extern const int a; int a = 2; 

invalid in C since C says that:

(C11, 6.7p4) β€œAll declarations in the same scope that relate to the same object or function must indicate compatible types”

In your case, they are not in the same area (different translation units), but C also says that:

(C11, 6.2.7p2) "All declarations related to the same object or function must be of a compatible type, otherwise the behavior is undefined."

As you break the rule above, you invoke undefined behavior.

Please note that the C90 has the same paragraphs.

+6
source share

A little late, but anyway.

I think it might work if you do something like this

in header.h:

 #ifndef HEADER_H_ #define HEADER_H_ #ifndef HAS_GLOB_VAR extern const int global_variable; #endif #endif 

and if you need to include a header in a file that actually defines the variable ( header.c ), you do something like

 #define HAS_GLOB_VAR #include "header.h" int global_variable = 17; ... 

In other files, you simply include the header and do not define HAS_GLOB_VAR .

+1
source share

You do not assign a value to global_variable, you define it.

0
source share

All Articles