我打算将对象声明为外部对象,但最终得到了几个对结构对象的 undefined reference
这是代码
gvars.h
#include <structsource.h> //houses the struct definition of newType
extern struct newType *myvars;
main.c
#include <structsource.h>
#include "gvars.h"
int main(int x){
struct newType *myvars = myvalue;
return 0;
}
其他.c
#include <structsource.h>
#include <others.h> //houses definition of others_func();
#include "gvars.h"
int otherfunc(){
others_func(myvars);
}
这就是它的工作原理。在 main 中,结构体变量 myvars
填充有 myvalue
。然后我想让它也可用于其他 c 文件。
将结构指针声明为外部的正确方法是什么?
最佳答案
int main(int myvalue){
struct newType *myvars = myvalue;
return 0;
}
myvars 是一个局部变量,而不是全局变量
但是
extern struct newType *myvars;
说 gloval var myvars 存在等
因为这是错误的,并且在 otherfunc() 中使用时没有定义全局变量 myvars,所以链接找不到它并说它未定义
<小时/>您可以将myvars的定义放在main之外作为全局变量,但可以在main内部对其进行初始化
struct newType *myvars;
int main(int myvalue){
myvars = ...; // myvalue is an int, to do myvars = myvalue has no sense
return 0;
}
附加说明:您可能对 main 函数接收的参数犯了错误,并且它与您期望的不同
关于c - 将结构指针对象/变量声明为 extern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54052116/