C 将结构指针对象/变量声明为外部对象
我打算将对象声明为一个extern,但最终得到了几个对struct对象的C 将结构指针对象/变量声明为外部对象,c,struct,extern,C,Struct,Extern,我打算将对象声明为一个extern,但最终得到了几个对struct对象的未定义引用 这是密码 gvars.h #include <structsource.h> //houses the struct definition of newType extern struct newType *myvars; #include//包含newType的结构定义 外部结构newType*myvars; main.c #include <structsource.h> #in
未定义引用
这是密码
gvars.h
#include <structsource.h> //houses the struct definition of newType
extern struct newType *myvars;
#include//包含newType的结构定义
外部结构newType*myvars;
main.c
#include <structsource.h>
#include "gvars.h"
int main(int x){
struct newType *myvars = myvalue;
return 0;
}
#包括
#包括“gvars.h”
int main(int x){
struct newType*myvars=myvalue;
返回0;
}
其他
#include <structsource.h>
#include <others.h> //houses definition of others_func();
#include "gvars.h"
int otherfunc(){
others_func(myvars);
}
#包括
#包括//houses others_func()的定义;
#包括“gvars.h”
int otherfunc(){
其他职能部门(myvars);
}
这就是它的工作原理。结构变量myvars
主要由myvalue
填充。然后我想让它也可以用于其他c文件
将结构指针声明为外部对象的正确方法是什么
int main(int myvalue){
struct newType *myvars = myvalue;
return 0;
}
myvars是一个局部变量,而不是全局变量
但是
表示gloval var myvars存在等
因为这是false,并且在otherfunc()中使用时没有定义全局变量myvars,所以链接找不到它,并说它未定义
您可以将myvars的定义放在main之外作为全局变量,但也可以在main内部初始化它
附加说明:可能您在主函数接收的参数方面出错,并且与您期望的语句不同extern struct newType*myvars
将myvars
声明为具有外部链接的标识符
当struct newType*myvars=myvalue时代码>出现在函数中,它声明myvars
是一个没有链接的标识符。因为它没有链接,所以不会链接到早期的声明。(此myvars
声明也是一个定义,因为它会导致创建对象。)
程序中没有具有外部链接的myvars
定义,因此第一个声明永远不会链接到定义
要使用外部链接创建myvars
的定义,必须将struct newType*myvars=myvalue代码>在函数的外部。您需要将指针设置为全局指针
// this is wrong as myvars is only exists in the main function scope
// and when you call any other function from main it stops to be accesible
int main(){
struct newType *myvars = myvalue;
/* .... */
}
如果myvalue
不是一个常量表达式,则需要在te函数体内对其进行初始化(例如main
)
main
有一个非常具体的参数,它们被称为argc
和argv
一个int
也不是指针,指向main
的参数与您给定的参数不匹配。。。等你应该得到更多的诊断,除了<代码>未定义的引用< /代码> @ ANTIHAAPALA,我已经修正了主要的论点,顺便说一下,<代码> MyValue>代码>对于NeXType数据类型来说是一个有效的值。@程序员:这不是一个有用的注释,它是以人们认为不放或粗鲁的方式呈现的。这是没有帮助的,因为了解范围不足以回答问题,真正理解如何提供外部定义需要理解链接和规则,了解什么使声明成为外部的,以及什么使某事物成为定义而不是声明。这些规则并不直截了当,在C标准中也没有以直接的方式呈现,也不能仅仅通过了解范围来解决。intmain(intx)
不是main
的正确声明。对于可移植程序,它应该是intmain(void)
或intmain(intargc,char*argv[])
,那么,您建议如何为myvars
赋值,以便我不会在others.c
中得到未定义的引用?您仍然没有告诉如何修复它。@AnttiHaapala ok我编辑了代码以添加一个可能的solution@DominicGuana更简单的方法是使myvars全球化,请参阅myvars的新版本answer@bruno你好我纠正了主要部分。现在可以编译了。谢谢
struct newType *myvars;
int main(int myvalue){
myvars = ...; // myvalue is an int, to do myvars = myvalue has no sense
return 0;
}
// this is wrong as myvars is only exists in the main function scope
// and when you call any other function from main it stops to be accesible
int main(){
struct newType *myvars = myvalue;
/* .... */
}
// Now it is global and can be used from other functions / compilation units
// you can initilaze this way if the myvalue is a contant expression
struct newType *myvars = myvalue;
int main(){
/* .... */
}
struct newType *myvars;
int main(){
myvars = myvalue;
/* .... */
}