c - 在 C 中的函数之间共享数据值

标签 c

<分区>

我在 dbinfo.h 中有一个简单的结构。

typedef struct {
   int fields;
} dbinfo;

在我的主程序中:

#include <string.h>
 ...
#include "dbinfo.h"
extern dbinfo *tst_info;

void main() {

tst_info = (dbinfo *) calloc(1, sizeof(dbinfo));

dbinfo.fields = 3;

printf("\n number of fields = %d"), getnumflds());
...
}

在另一个文件 utilities.c 中我有

#include "dbinfo.h"
extern dbinfo *tst_info;

int getnumflds() {

   return tst_info.fields;
}

当我尝试链接时,我在 tst_info 的 utilities.c 中得到 undefined symbol 。 如果我删除 extern,则不会得到未解析的符号,但字段的值为 0。

我做错了什么?

我只是希望能够在单独编译的其他函数中使用和更改在 main 中设置的“字段”的值。

自从我使用 C 以来已经有很长一段时间无法访问这些神经元了!

最佳答案

所有 tst_info 的定义都必须是 extern except one。某个目标文件中变量的 extern 关键字告诉链接器不要在数据段中为其分配空间,因为该变量的存储将在其他目标文件中提供。如果所有目标文件都将变量定义为extern,则没有目标文件为其提供存储。

你可以阅读更多关于这个的信息,而不是在这篇文章中处理: https://stackoverflow.com/a/1433387/773113

关于c - 在 C 中的函数之间共享数据值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45442669/

相关文章:

c - 了解递归函数

c - 为什么 scanf 和 printf 函数的语法中有一个指向常量的指针?

c - 使用 dlopen 访问 CMake 生成的动态库

c++ - 快速 strlen 函数与别名规则

c - 算法的递归关系

c - 我应该在哪里列出 c 和 makefile 中的 header

c - 在用 c 语言写入文件时,二进制模式和文本模式之间是否存在性能差异?

c - 如何从命令提示符编译和运行汇编程序源代码?

c - 有符号整数和无符号整数是一一对应的吗?

C如何在不使用图形库或任何其他库函数的情况下绘制点/设置像素