c - 如何让 typedef 结构跨多个文件文件工作?错误 : invalid use of undefined type 'struct data'

标签 c function struct typedef

我的 main.c 文件中的结构声明。我声明了函数原型(prototype)但未显示。

typedef struct data
{
      int t;
      float tp, tf, tt;
} reactorData;


int main()
{
  reactorData reactorOne[21];

  //other stuff
}

这是在我的 function.c 文件中给我错误的函数。具体在 printf() 语句中。

typedef struct data reactorData; //this is what I have up top


void reactorOutput(reactorData  * data)
{
   int c;
   for (c=0;c<21;c++)
   {

    printf(" %3d\t %.0f\t %.0f\t  %.0f\n",c, data[c].tp, data[c].tf, data[c].tt);
   }
}

错误如下: |错误:无效使用未定义类型“结构数据”|

该函数本身运行良好/我已经在 main 中对其进行了测试。只有当我在 functions.c 中有它时它才不起作用。

最佳答案

必须在不同编译单元之间共享的新结构和类型定义最好放在头文件中:

// mystructh.h
#ifndef MYSTRUCT_H
#define MYSTRUCT_H

typedef struct data
{
      int t;
      float tp, tf, tt;
} reactorData;

void reactorOutput(reactorData  * data);

// other stuff

#endif

然后在其他 c 文件中你必须包含标题

ma​​in.c

#include <stdio.h>
#include "mystruct.h"

int main(void)
{
  reactorData reactorOne[21];


  // for example
  reactorOutput(reactorOne);

  //other stuff
}

函数.c

// functions.c
#include "mystruct.h"

void reactorOutput(reactorData  * data)
{
   int c;
   for (c=0;c<21;c++)
   {

    printf(" %3d\t %.0f\t %.0f\t  %.0f\n",c, data[c].tp, data[c].tf, data[c].tt);
   }
}

您的版本的问题是 struct data 仅在 main.c 中定义。 当编译器编译functions.c时,它并不知道struct data是什么。 这就是为什么您必须使用上面显示的实时头文件。

关于c - 如何让 typedef 结构跨多个文件文件工作?错误 : invalid use of undefined type 'struct data' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49847327/

相关文章:

c - (char*)malloc(sizeof(char)) 分配多个字符?

c - Arduino 将十进制转换为二进制再转换为十进制

c - 函数错误 'expected expression before char'?

python - 用结构重建我的波形文件

c++ - 错误:预期的类名(链接列表C++)

c - 结构填充信息

c - C中的指针转换代码是什么意思

c - 跳过 for 循环的一次迭代

c++ - 如何编写可以接受数组或 vector 的函数?

azure - 尝试了解 Azure Durable Function 上下文