Most elegant way to share a C array

后端 未结 4 468
暗喜
暗喜 2021-01-18 22:01

I have to turn back to (embedded) C after some lengthy time with C++, and have the following problem:

I have a source module which is included a lot of times, let\'s

相关标签:
4条回答
  • 2021-01-18 22:25

    I often put the definition in the header (this is frowned upon, I know). It keeps the definition and declaration close together, which is a Good Thing.

    /* file.c */
    #define FILE_C 1
    #include "file.h"
    

    .

    /* file.h */
    #ifndef FILE_H
    #define FILE_H 1
    
    #define BIG_SIZE 13
    
    #if FILE_C 
    char the_array[BIG_SIZE];
    #else
    extern char the_array[BIG_SIZE];
    #endif
    
    #endif /* FlLE_H */
    

    .

     /* other_file.c */
    #include "file.h"
    

    There is no risk of doing it wrong: the linker will complain if you do it wrong.

    BTW a similar way to basically do the same, but maybe a bit more readable, is:

    /* file.h */
    #ifndef FILE_H
    #define FILE_H 1
    
    #if FILE_C
    #define EXTERN /**/
    #else
    #define EXTERN extern
    #endif
    
    #define BIG_SIZE 13
    
    EXTERN char the_array[BIG_SIZE];
    
    ...
    
    #undef EXTERN
    #endif /* FlLE_H */
    
    0 讨论(0)
  • 2021-01-18 22:29

    Create a new function at utilities.c called something like "get_important_array" that just returns a pointer to array and put the prototype at utilities.h. After that, when you put the utilities.h at worker.c you'll have important_array access in a simple, and organized way.

    0 讨论(0)
  • 2021-01-18 22:39

    What you have is the canonical way to do it: have an extern declaration in the header file, and define the variable in the .c file.

    my array will be an undefined symbol in worker.c

    No, it won't. Your code will compile and link just fine.

    0 讨论(0)
  • 2021-01-18 22:43

    Having one declaration (extern...) in each translation unit and exactly one definition is the most elegant way to do this.

    So leave the extern char important_array in the header and char important_array in one of the .c files.

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