gpt4 book ai didi

c - 访问不同路径中存在的不同 .c 文件中的全局变量值

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

我有 2 个文件:Sod/iload/iload.cItem/itemrule/itemrule.c,我想访问 iload.c 中定义的变量,该变量在 itemrule.c 中定义。

为此,我在 iload.c 中创建并定义了一个全局变量,并尝试使用 extern 关键字在 itemrule.c 中访问该变量,但它始终为 0。

我担心这可能是因为文件有不同的路径,有谁知道我如何访问这个变量?

最佳答案

通常的用法是在头文件中使用 extern 声明,并将其包含在需要全局变量的地方。

// foo.h
// Make the global visible in any C file that includes this header.
extern int my_global_var;
// foo.c
#include "foo.h" // Not really needed here, but fine.
int my_global_var;
...
// bar.c
#include <stdio.h>
#include "foo.h" // This one makes the global visible in the rest of the file.

void do_something(void) {
printf("my global var's value is: %d\n", my_global_var);
}

请注意,在任何显着大小或复杂性的程序中使用这样的全局变量可能会导致困惑、容易出错且难以更改的代码。这不是一个很好的模式。

关于c - 访问不同路径中存在的不同 .c 文件中的全局变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56695826/

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