shared global variables in C

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

    In the header file write it with extern. And at the global scope of one of the c files declare it without extern.

    0 讨论(0)
  • 2020-11-28 20:42

    In one header file (shared.h):

    extern int this_is_global;
    

    In every file that you want to use this global symbol, include header containing the extern declaration:

    #include "shared.h"
    

    To avoid multiple linker definitions, just one declaration of your global symbol must be present across your compilation units (e.g: shared.cpp) :

    /* shared.cpp */
    #include "shared.h"
    int this_is_global;
    
    0 讨论(0)
  • 2020-11-28 20:50

    You put the declaration in a header file, e.g.

     extern int my_global;
    

    In one of your .c files you define it at global scope.

    int my_global;
    

    Every .c file that wants access to my_global includes the header file with the extern in.

    0 讨论(0)
  • 2020-11-28 20:52

    If you're sharing code between C and C++, remember to add the following to the shared.hfile:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    extern int my_global;
    /* other extern declarations ... */
    
    #ifdef __cplusplus
    }
    #endif
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 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.

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