Does C provide a way to declare an extern variable as 'read-only', but define it as writeable?

前端 未结 2 982
栀梦
栀梦 2021-01-19 12:20

I\'m developing a hardware abstraction library for an embedded product using GCC C. Within the library there is a variable that should be read-only to the application that l

相关标签:
2条回答
  • 2021-01-19 12:34

    Within the library there is a variable that should be read-only to the application that links the library, but can be modified from within the compilation unit that defines it.

    The solution is to use object-oriented design, namely something called private encapsulation.

    module.h

    int module_get_x (void);
    

    module.c

    static int x;
    
    int module_get_x (void)
    {
      return x;
    }
    

    main.c

    #include "module.h"
    
    int main(void)
    {
      int value = module_get_x();
    }
    

    If the variable must be read-write inside the module, then this is the only proper way to do this. All other ways are just some flavour of spaghetti programming.

    0 讨论(0)
  • 2021-01-19 12:54

    You can use pointer to get past the issue.

    module.c

    static int readwrite = 0;
    int const * const readonly = &readwrite;
    

    module.h

    extern int const * const readonly;
    

    If there is no reason to expose address of the variable, you should prefer Lundins getter approach to have proper encapsulation.

    0 讨论(0)
提交回复
热议问题