mercredi 31 décembre 2014

C/C++: Using `extern const` in header files to make global variables read only


I was experimenting with GCC and found out that you can declare variables const in header files but keep them mutable in implementation files.


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; /* This is an error and will not compile! */
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.





Aucun commentaire:

Enregistrer un commentaire