shared global variables in C

前端 未结 6 653
星月不相逢
星月不相逢 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:55

    There is a cleaner way with just one header file so it is simpler to maintain. In the header with the global variables prefix each declaration with a keyword (I use common) then in just one source file include it like this

    #define common
    #include "globals.h"
    #undef common
    

    and any other source files like this

    #define common extern
    #include "globals.h"
    #undef common
    

    Just make sure you don't initialise any of the variables in the globals.h file or the linker will still complain as an initialised variable is not treated as external even with the extern keyword. The global.h file looks similar to this

    #pragma once
    common int globala;
    common int globalb;
    etc.
    

    seems to work for any type of declaration. Don't use the common keyword on #define of course.

提交回复
热议问题