代码之家  ›  专栏  ›  技术社区  ›  Delan Azabani

不带类型的外部

  •  5
  • Delan Azabani  · 技术社区  · 14 年前

    如果 extern

    extern <type> <name>;
    

    我该怎么办 外部

    struct {
        char **plymouthThemes;
        char *plymouthTheme;
    } global;
    

    我试过了

    extern global;
    

    没有任何类型,也不起作用。

    3 回复  |  直到 14 年前
        1
  •  5
  •   Armen Tsirunyan    14 年前

    您需要命名结构并将其放入一个.h文件中,或者在使用global的每个源文件中手动包含该定义。这样地

    ///glob.h
        struct GlobalStruct
        {
           ///char** ...
           ///
        };
    
    ///glob.cpp
       #include "glob.h"
       struct GlobalStruct global; 
    
    ///someOtherFile.cpp
    #include "glob.h"
    
    extern struct GlobalStruct global; 
    
        2
  •  2
  •   Vovanium    14 年前

    如果不想命名结构,可以使用以下常用方法:

    --- global.h: (file with global struct definition):
    
    #ifdef GLOBAL_HERE /* some macro, which defined in one file only*/
    #define GLOBAL
    #else
    #define GLOBAL extern
    #endif
    
    GLOBAL struct {
        char **plymouthThemes;
        char *plymouthTheme;
    } global;
    
    ---- file1.c (file where you want to have global allocated)
    
    #define GLOBAL_HERE
    #include "global.h"
    
    ---- file2.c (any oher file referencing to global)
    
    #include "global.h"
    

    宏全局是有条件定义的,因此它的用法将在定义前加上“extern”,除了定义全局的源。在这里定义GLOBAL_时,变量将变为非外部变量,因此它将被分配到此源的输出对象中。

    #define extern
    

    这会导致预处理器删除extern(替换为空字符串)。但不要这样做:重新定义标准关键字是

        3
  •  1
  •   Noctis    9 年前

    其思想是,您只需要声明一个,但仍然需要在使用该变量的其他文件中定义该变量。该定义包括类型(在您的示例中是头定义结构,因此需要包含)和 extern 关键字让编译器知道声明位于不同的文件中。

    这是我的例子

    struct mystruct{
        int s,r;
    };
    

    扩展1.c

    #include "ext.h"
    
    struct mystruct aaaa;
    
    main(){
        return 0;
    }
    

    扩展2.c

    #include "ext.h"
    
    extern struct mystruct aaaa;
    
    void foo(){
        aaaa;
    }
    

    扩展3.c

    #include "ext.h"
    
    extern struct mystruct aaaa;
    
    void foo2(){
        aaaa;
    }