C: undefined reference to a variable when using extern

社会主义新天地 提交于 2021-02-07 00:14:27

问题


I try to declare a global variable 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
#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:

undefined reference to `config':

Main program:

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

main() {
    config.num = 10;
}

Why is it?


回答1:


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 -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.



来源:https://stackoverflow.com/questions/23367326/c-undefined-reference-to-a-variable-when-using-extern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!