How to define an array of strings of characters in header file?

后端 未结 5 449
眼角桃花
眼角桃花 2021-02-04 04:05

I have many different 3 axis sensors I am writing test code for. In the C files for each of them, I have the same char string defined:

char axis[3][8] = {\"X\",          


        
相关标签:
5条回答
  • 2021-02-04 04:50

    If you must put it in a header file, use extern or static:

    // option 1
    // .h
    extern char axis[3][8];
    
    // .c
    char axis[3][8] = { "X", "Y", "Z" };
    
    // option 2
    // .h
    static char axis[3][8] = { "X", "Y", "Z" };
    

    Extern tells the linker that there is a global variable named axis defined in one of our implementation files (i.e. in one .c file), and I need to reference that here.

    static, on the other hand, tells the compiler the opposite: I need to be able to see and use this variable, but don't export it to the linker, so it can't be referenced by extern or cause naming conflicts.

    0 讨论(0)
  • 2021-02-04 04:50

    Put this in your header file

    extern char axis[3][8];
    

    and keep this in a C file:

    char axis[3][8] = {"X", "Y", "Z"};
    
    0 讨论(0)
  • 2021-02-04 05:03

    In order to avoid linker errors, you have to declare your array as extern in a header file, and then define the array once in one of your code modules.

    So for instance:

    //myheader.h
    extern const char* axis[3];
    

    then in another code module somewhere:

    //myfile.c
    const char* axis[3] = { "X", "Y", "Z" };
    
    0 讨论(0)
  • 2021-02-04 05:03

    Add this to your header:

    extern char *axis[];
    

    Add this to one source file in your project:

    char *axis[] = { "X", "Y", "Z", "Time", "Space", "The Scary Door" };
    
    0 讨论(0)
  • 2021-02-04 05:03

    Michael Barr (Netrino) advises against the declaration of storage in a header file. Likewise, the Netrino embedded system coding standard does not condone the use of extern'ed storage in headers.

    I generally agree with these principles, and I've found it to be a good idea to extern storage into the C files that need it, and only those.

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