Making C Module Variables Read Only

I would like to provide a read-only modular variable for client modules. A few solutions:

1 . The most common:

// module_a.c
static int a;

int get_a(void)
{
    return a;
}

// module_a.h
int get_a(void);

This allows you to use one function for each variable, one function call (I think both runtime and readability), and one copy for each read. Assuming no optimizer 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 it, except that the client needs to read the contents of the pointer. In addition, for each variable is required for read-only pointer extern constto const.

3. , , , extern struct. module_name->a , .

4. get_a(void). - , .

:

  • , ? ?

  • , ?

, - , , , .

+7
3

№ 4, , , . №2 №3 - . (const - "" , ). # 1 , .

+4

, , :

static inline int get_a(void)
{
    extern int a_var;
    return a_var;
}

. .

: , , C. , :

extern int my_project_a;

. , , ? , 1) , 2) . № 1 , . №2 .

nm /lib/libc.so . , libc , . , __host_byaddr_cache. C, :

extern void *__host_byaddr_cache;
__host_byaddr_cache = NULL;

, , . static - , .

- - , , .

+2
  • :

There is a reason why this is the most common. This is the best.

I do not think the performance hit was significant enough to worry in most situations.

+1
source

All Articles