【问题标题】:How to access variables declared in other files in C? [duplicate]如何访问 C 中其他文件中声明的变量? [复制]
【发布时间】:2020-08-24 16:50:55
【问题描述】:

您好,这可能是一个愚蠢的问题,但我在网上查看后不知道如何解决这个问题。在project/a/aa/filea.h 下我们将调用filea.h 的文件中,我声明了一个变量(全局)bool is_testing = false;

project/b/bb/fileb.c 下的另一个名为fileb.c 的文件中,我有以下内容:

#include <a/aa/filea.h>
...
int ex_func(void)
{
  is_testing = true;
}

我在尝试编译时收到此错误:filea.h:19: first defined here。有谁知道如何解决这个问题?

【问题讨论】:

标签: c extern variable-declaration linkage one-definition-rule


【解决方案1】:

标题中的这个声明

bool is_testing = false;

也是变量的定义。因此,该变量将被定义多次,因为标题将包含在不同的翻译单元中。

放在表头

extern bool is_testing;

并在某些模块中写入

bool is_testing = false;

例如定义函数的地方..

【讨论】:

    猜你喜欢
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2013-05-15
    • 1970-01-01
    • 2018-10-16
    • 2013-04-30
    相关资源
    最近更新 更多