C the same global variable defined in different files

前端 未结 6 951
我在风中等你
我在风中等你 2020-12-04 17:09

I am reading this code from here(in Chinese). There is one piece of code about testing global variable in C. The variable a has been defined in the file t

6条回答
  •  春和景丽
    2020-12-04 17:47

    The piece of code seems to break the one-definition rule on purpose. It will invoke undefined behavior, don't do that.

    About the global variable a: don't put definition of a global variable in a header file, since it will be included in multiple .c files, and leads to multiple definition. Just put declarations in the header and put the definition in one of the .c files.

    In t.h:

    extern int a;
    

    In foo.c

    int a;
    

    About the global variable b: don't define it multiple times, use static to limit the variable in a file.

    In foo.c:

    static struct {
       char a;
       int b;
    } b = { 2, 4 };
    

    In main.c

    static int b;
    

提交回复
热议问题