【问题标题】:Practical use of extern in C? [duplicate]在 C 中实际使用 extern? [复制]
【发布时间】:2015-12-30 23:00:34
【问题描述】:

extern 在 C 中的实际用途是什么?跨多个文件使用时,全局变量的工作方式不一样吗?

文件头.h

int i;

这包含在多个文件中并按预期工作。那么 extern 的正确用法是什么?

【问题讨论】:

  • 一个原因是,如果您使用某些库,它会为您的程序提供更多的可读性。你会在你的程序中声明extern int i; 。这清楚地表明您正在使用未在此处声明的变量 i。

标签: c


【解决方案1】:

extern 声明一个全局变量(通常在头文件中)。它应该在一个源文件中定义。否则,根据链接器的智能程度,您最终可能会遇到错误或同一变量的多个定义。不过,现代链接器可能会为您解决这个问题。

【讨论】:

    【解决方案2】:

    您可以使用extern 访问不同文件中的变量...

    例如看到这个:

    file1.c

    // Integer with external binding
    int global1 = 10;
    // REFERENCE to an external defined variable defined in file2.c
    extern int global2;
    // Integer with internal binding (not accessible with extern from other files)
    static int internal1 = 20;
    
    void print1() {
        printf("%d, %d, %d", global1, global2, internal);
    }
    

    file2.c

    // REFERENCE to an external defined variable defined in file1.c
    extern int global1;  
    
    // Integer with external binding
    int global2 = 20;
    
    void print2() {
        // you wont be able to reach internal1 here! Even with extern!
        printf("%d, %d", global1, global2);
    }
    

    你看,external 关键字告诉编译器全局变量存在,但在另一个文件中。您可以引用在其他地方声明的变量(例如,在外部库或另一个目标文件中。它的链接器内容)。此外,它还将大大提高源代码的可读性,并有助于避免同名变量!使用它的好习惯...

    顺便说一句:全局变量是默认的extern。添加static 会将它们更改为内部变量!

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 2012-09-15
      • 1970-01-01
      • 2012-11-20
      • 2013-10-12
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 2021-07-15
      相关资源
      最近更新 更多