C语言 C: 使用 extern 时对变量的未定义引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23367326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:02:55  来源:igfitidea点击:

C: undefined reference to a variable when using extern

cglobal-variablesextern

提问by Halona

I try to declare a global variable config:

我尝试声明一个全局变量config

//general.h

struct config_t {
    int num;
};

extern struct config_t config;  //The global variable

Then I define config variable in general.c:

然后我在中定义配置变量general.c

//general.c
#include "general.h"

struct config_t config = {
    num = 5;
};

But, when I try to use the global variable 'config' in my main function, I get the error:

但是,当我尝试在主函数中使用全局变量 'config' 时,出现错误:

undefined reference to `config':

Main program:

主程序:

//main.c
#include "general.h"

main() {
    config.num = 10;
}

Why is it?

为什么?

采纳答案by Sergey L.

This looks like a linker error. You need to make sure you link your executable properly:

这看起来像是链接器错误。您需要确保正确链接您的可执行文件:

cc -c general.c
cc -c main.c
cc general.o main.o
./a.out

The -cflag instructs your compiler not to link yet. In order to link the object file containing configneeds to be available at that moment.

-c标志指示您的编译器不要链接。为了链接目标文件,包含config需要在那一刻可用。