2

为什么要extern在以下代码中使用关键字:

头文件.h

float kFloat; // some say I should write 'extern float kFloat;', but why?

文件.c

#include <stdio.h>
#include "Header.h"

float kFloat = 11.0f;

主程序

#include <stdio.h>
#include "Header.h"

int main(int argc, const char * argv[])
{
    printf("The global var is %.1f\n", kFloat);

    return 0;
}

此代码有效。全局变量 kFloat 默认为外部链接和静态生命周期。

输出是:

全局变量为 11.0

我不明白在哪种情况下会出现问题,谁能给我一个崩溃的例子?

4

5 回答 5

8
extern float kFloat;

declares kFloat without defining it.

but:

float kFloat;

also declares kFloat but is a tentative definition of kFloat.

Adding extern just suppresses the tentative definition. In a header file you only want declarations, not definitions.

If the tentative definition is included in several source files, you will end up having multiple definitions of the same object which is undefined behavior in C.

于 2013-10-05T14:31:29.007 回答
3

Always put the definition of global variables(like float kFloat;) in the .c file, and put the declarations (like extern float kFloat;) in the header.

Otherwise when multiple .c files include the same header, there will be a multiple definition error.

于 2013-10-05T14:32:07.090 回答
2

extern indicates that a variable is defined somewhere in the project (or outside function block) that you want to use. It does not allocate memory for it since you are telling the compiler that this is defined else where.

A variable must be defined once in one of the modules of the program. If there is no definition or more than one, an error is produced, possibly in the linking stage.

Definition refers to the place where the variable is created or assigned storage; declaration refers to places where the nature of the variable is stated but no storage is allocated.

And since it will be accessible elsewhere it needs to be static.

于 2013-10-05T14:31:08.237 回答
2

首先,您的代码正在编译很奇怪。它应该kFloatFile.c.

其次,如果您尝试在两个文件中使用公共变量,则不应在header.h. 您应该extern在头文件中使用关键字,以便包含该文件的文件header.h知道它已在外部定义。

现在,您可以在任何 c 文件中全局定义该变量,然后将该变量用作公共变量。

于 2013-10-05T14:36:28.173 回答
2

为什么我要使用 extern ...?

好吧,你不应该。干净利落。因为您不应该使用全局变量,它们是唯一需要extern关键字的变量。

每当您想使用全局变量时,请三思。在绝对最大值下,您可能需要使用具有文件范围的变量(使用static关键字),通常这样的变量会伴随着一些操作/使用其值的函数,但变量本身不应该超出文件的范围。使用全局变量只会导致难以处理的代码,如果不引入大量错误几乎不可能更改。

于 2013-10-05T14:50:38.690 回答