首页 文章

C中共享的全局变量

提问于
浏览
74

如何创建在C中共享的全局变量?如果我将它放在头文件中,那么链接器会抱怨已经定义了变量 . 是在我的一个C文件中声明变量并手动将 extern s放在要使用它的所有其他C文件的顶部的唯一方法吗?这听起来并不理想 .

6 回答

  • 14

    在头文件中用 extern 写它 . 并且在其中一个c文件的全局范围内声明它没有 extern .

  • 21

    在一个头文件(shared.h)中:

    extern int this_is_global;
    

    在要使用此全局符号的每个文件中,包含包含extern声明的标头:

    #include "shared.h"
    

    要避免多个链接器定义, just one declaration of your global symbol must be present across your compilation units (例如:shared.cpp):

    /* shared.cpp */
    #include "shared.h"
    int this_is_global;
    
  • 84

    在头文件中

    头文件

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

    在包含您希望全局生存的文件的文件中:

    #define MAIN_FILE
    #include "share.h"
    

    在需要extern版本的其他文件中:

    #include "share.h"
    
  • 57

    您将声明放在头文件中,例如

    extern int my_global;
    

    在您的一个.c文件中,您可以在全局范围内定义它 .

    int my_global;
    

    每个想要访问 my_global 的.c文件都包含带有 extern 的头文件 .

  • 4

    如果您在C和C之间共享代码,请记住将以下内容添加到 shared.h 文件中:

    #ifdef __cplusplus
    extern "C" {
    #endif
    
    extern int my_global;
    /* other extern declarations ... */
    
    #ifdef __cplusplus
    }
    #endif
    
  • 1

    只有一个头文件有一个更简洁的方法,因此维护起来更简单 . 在带有全局变量的头文件中,每个声明前缀都带有一个关键字(我使用common),然后在一个源文件中包含它就像这样

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

    和这样的任何其他源文件

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

    只是确保你没有初始化globals.h文件中的任何变量,否则链接器仍然会抱怨,因为初始化变量即使用extern关键字也不会被视为外部变量 . global.h文件看起来与此类似

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

    似乎适用于任何类型的声明 . 当然不要在#define上使用common关键字 .

相关问题