How to declare a structure in a header that is to be used by multiple files in c?

后端 未结 3 1830
北海茫月
北海茫月 2020-11-30 16:24

If I have a source.c file with a struct:

struct a { 
    int i;
    struct b {
        int j;
    }
};

How can this struct be used in anoth

3条回答
  •  -上瘾入骨i
    2020-11-30 17:21

    For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.

    The extern declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern in a header file like:

    extern struct a myAValue;
    

    Then, in one source file, define the actual variable:

    struct a myAValue;
    

    If you forget to do this or accidentally define it in two source files, the linker will let you know about this.

提交回复
热议问题