gpt4 book ai didi

c - 外部没有区别

转载 作者:太空宇宙 更新时间:2023-11-04 00:16:27 24 4
gpt4 key购买 nike

我在test2.h 中定义了一个全局变量

#ifndef TEST2_H
#define TEST2_H

int test_var;

void use_it(void);

#endif

并在两个不同的文件中再次定义它,test.c

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

int test_var;

int main() {
printf("The test_var is: %d\n", ++test_var); // prints 1
use_it(); // prints 2
}

test2.c

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

int test_var;

void use_it() {
printf("The test_var is: %d", ++test_var);
}

我用 extern int test_var 替换了 test_var 的定义,得到了相同的结果。也就是说,在这两种情况下,test.ctest2.c 这两个文件都可以访问全局变量 test_var。我的印象是,如果没有 extern,每个文件都会有自己的 test_var 副本。观察表明情况并非如此。那么 extern 什么时候真正做某事呢?

最佳答案

您最终得到了 test_var 的两个副本,这是未定义的行为。

(C99, 6.9p5) "If an identifier declared with external linkage is used in an expression (other than as part of the operandof a sizeof operator whose result is an integer constant), somewhere in the entire program there shall be exactly one external definition for the identifier; otherwise, there shall be no more than one"

在您的情况下,链接器可能对您很好并合并了两个符号,但这仍然不可移植并且是未定义的行为。如果您使用的是 GNU 链接器,则可以使用 --warn-common 获取警告(如果需要错误,则可以使用 --fatal-warnings)。

要解决您的问题,请将 extern 说明符放在 .h 文件中 test_var 的声明中,并删除其中一个定义test_var(例如 test.c 文件中的那个)。

关于c - 外部没有区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com