C:使用extern时未定义对变量的引用 [英] C: undefined reference to a variable when using extern
本文介绍了C:使用extern时未定义对变量的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试声明全局变量 config
:
//general.h
struct config_t {
int num;
};
extern struct config_t config; //The global variable
然后我在 general.c
中定义配置变量:
Then I define config variable in general.c
:
//general.c
#include "general.h"
struct config_t config = {
num = 5;
};
但是,当我尝试在主函数中使用全局变量'config'时,出现错误:
But, when I try to use the global variable 'config' in my main function, I get the error:
undefined reference to `config':
主程序:
//main.c
#include "general.h"
main() {
config.num = 10;
}
为什么?
推荐答案
这看起来像是链接器错误.您需要确保正确链接可执行文件:
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
-c
标志指示编译器尚未链接.为了链接包含 config
的目标文件,该时刻需要可用.
The -c
flag instructs your compiler not to link yet. In order to link the object file containing config
needs to be available at that moment.
这篇关于C:使用extern时未定义对变量的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文