I was experimenting with GCC and found out that you can declare variables const
in header files but keep them mutable in implementation files.
EDIT: This does actually not work, check my own answer.
header.h:
#ifndef HEADER_H_
#define HEADER_H_
extern const int global_variable;
#endif
header.c:
int global_variable = 17;
This makes global_variable
modifiable to the implementation but const
to every file that includes header.h
.
#include "header.h"
int main(void)
{
global_variable = 34; /* "header.h" prevents this type of assignment. */
return 0;
}
Is this technique used in practise?
People often recommend using get
-functions to retrieve global state when building interfaces in C. Are there any advantages to that approach over this?
To me this approach seems to be a lot more clearer and does not have the added overhead of a function call each time someone tries to access global_variable
.