How to get a typedef struct to work across multiple files files? error: invalid use of undefined type 'struct data'

How to get a typedef struct to work across multiple files files? error: invalid use of undefined type 'struct data'

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

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);
   }
}

错误如下: |错误:无效使用未定义类型 'struct data'|

该函数本身工作得很好/我已经在 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 文件中你必须包含头文件

main.c

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

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


  // for example
  reactorOutput(reactorOne);

  //other stuff
}

functions.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是什么。 这就是为什么你必须使用上面显示的实时头文件。