c - 源文件中的static/extern有什么用?

标签 c static scope extern

当我编译许多文件时,我对会发生什么有一个非常复杂的概念 - 主要是当涉及到从一个文件到另一个文件的可见性时。根据我的阅读,static 将变量或函数的范围限制为文件本身。 extern 做相反的事情。由此,我希望能够并简单地从任何文件中读取全局外部。尽管如下所示,但这在实践中不起作用。

ma​​in.c:

#include <stdio.h>

int main(void){
    printf("%d\n", b); // b is extern global
    return 0;
}

交流电:

static int a = 40;

公元前:

extern int b = 20;

我什至无法编译:

> gcc main.c a.c b.c -o test
b.c:1:12: warning: ‘b’ initialized and declared ‘extern’ [enabled by default]
 extern int b = 20;
            ^
main.c: In function ‘main’:
main.c:4:20: error: ‘b’ undeclared (first use in this function)
     printf("%d\n", b); // b is extern global

最佳答案

你做错了。当我们写 extern int b 时,这意味着一个名为 b 的整数类型变量已经声明。我们可以多次声明这个声明如所须。 (记住声明可以进行任意多次)。通过外部变量,我们可以在程序的任何地方使用变量,前提是我们知道它们的声明并且变量在某处定义。

正确的做法是

ma​​in.c:

#include <stdio.h>

extern int b;   //declaration of b
 int main(void){
    printf("%d\n", b); // using b 
    return 0;
}

公元前:

int b = 20;   //definition here

并编译为gcc main.c b.c -o test

我省略了 a.c,因为它在这个例子中什么都不做。 要了解有关外部人员的更多信息,请访问此站点。它的内容非常好 http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/

关于c - 源文件中的static/extern有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969939/

相关文章:

c - <string.h> 和 <strings.h> 的区别

objective-c - C 库的 Objective C 包装器 : wrapping calls that return Obj-C objects

Java:如果枚举常量本质上是静态的,它如何能够有一个构造函数和与之关联的方法

c# - (嵌套)自定义对象列表中的列表

javascript - 更改原型(prototype)中的值在 JavaScript 中不起作用

c - 将两个数组的条目合并为另一个数组的偶数和奇数条目。

android - 处理 appwidget 的多个实例

c++ - 在 for 的括号中定义变量

javascript - 如何根据作用域/闭包更新解构的 JavaScript 变量?

c - 词法分析器: how to identify the end of a token