I was experimenting with GCC and found out that you can declare external variables const
in header files but keep them mutable in implementation files.
EDIT: This does actually not work. The only reason I got my test code to compile 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 feature to use for keeping global_variable
readonly to the users of header.h
but keeping them modifable by the implementation (header.c
).
NOTE: The following code is just an example on how this way of declaring will prevent assignment to global_variable
.
#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 technique in practise before. I start to wonder if it is valid.
Is this well defined behaivor or is this an error that GCC fails to warn me about?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…