c - 将结构指针对象/变量声明为 extern

标签 c struct extern

我打算将对象声明为外部对象,但最终得到了几个对结构对象的 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/

相关文章:

java - java 的 sleep() 和 c 的 sleep() 之间有什么区别?

c - 获取对存储在 GHashTable 中的键的引用

c - 此代码是否由 C 标准保证?

c - C 中的外部结构

c++ - 外部未命名结构对象定义

objective-c - 尝试制作圆角 UIImage 时的性能问题(使用 mask )

fprintf() 的跨平台宏包装器

objective-c - Objective-C 中的全局变量 - extern 和 .m 文件声明顶部的差异

c - 结构复制的效率

c - 类型转换结构指针