Making C module variables accessible as read-only

c, readonly

Solution

Concerning option #4, I'm not sure you can make it inline if the variable isn't accessible outside the implementation file. I wouldn't count options #2 and #3 as truly read-only. The pointer can have the constness cast away and be modified (const is just a compiler "warning", nothing concrete). Only option #1 is read-only because it returns a copy.

Problem

I would like to give a module variable a read-only access for client modules. Several solutions: 1. The most common one: ``` // module_a.c static int a; int get_a(void) { return a; } // module_a.h int get_a(void); ``` This makes one function per variable to share, one function call (I am thinking both execution time and readability), and one copy for every read. Assuming no optimizing linker. 2. Another solution: ``` // module_a.c static int _a; const int * const a = &_a; // module_a.h extern const int * const a; // client_module.c int read_variable = *a; *a = 5; // error: variable is read-only ``` I like that, besides the fact that the client needs to read the content of a pointer. Also, every read-only variable needs its `extern const` pointer to `const`. 3. A third solution, inspired by the second one, is to hide the variables behind a struct and an extern pointer to struct. The notation `module_name->a` is more readable in the client module, in my opinion. 4. I could create an inline definition for the `get_a(void)` function. It would still look like a function call in the client module, but the optimization should take place. My questions: Is there a best way to make variables modified in a module accessible as read-only in other modules? Best in what aspect? Which solutions above would you accept or refuse to use, and why? I am aware that this is microoptimization - I might not implement it - but I am still interested in the possibility, and above all in the knowing.

Original source