shared global variables in C

前端 未结 6 597
星月不相逢
星月不相逢 2020-11-28 20:27

How can I create global variables that are shared in C? If I put it in a header file, then the linker complains that the variables are already defined. Is the only way to de

6条回答
  •  無奈伤痛
    2020-11-28 20:54

    In the header file

    header file

    #ifndef SHAREFILE_INCLUDED
    #define SHAREFILE_INCLUDED
    #ifdef  MAIN_FILE
    int global;
    #else
    extern int global;
    #endif
    #endif
    

    In the file with the file you want the global to live:

    #define MAIN_FILE
    #include "share.h"
    

    In the other files that need the extern version:

    #include "share.h"
    

提交回复
热议问题