如何在另一个文件中使用.c文件中定义的结构

cit*_*ity 3 c

我的测试代码如下:

main1.c:

#include <stdio.h>
extern struct tt ;
int main()
{
    struct tt y;
    y.a=255;
    y.b=0;
    printf("tt->a=%#x   ,tt->b=%#x \n",y.a,y.b);
}
Run Code Online (Sandbox Code Playgroud)

main2.c:

#include<stdio.h>

 struct tt
{
    int a;
    int b;
};
Run Code Online (Sandbox Code Playgroud)

生成文件:

main: main1.o
    gcc -o main main1.o
main1.o:  main2.c main1.c
Run Code Online (Sandbox Code Playgroud)

但编译器报告:

cc    -c -o main1.o main1.c
main1.c:2: warning: useless storage class specifier in empty declaration
main1.c: In function ‘main’:
main1.c:5: error: storage size of ‘y’ isn’t known
make: *** [main1.o] Error 1
Run Code Online (Sandbox Code Playgroud)

如何在.c文件中编写代码使用另一个.c文件中定义的结构?

谢谢你的帮助!

chr*_*ock 6

您需要struct在两个.c文件都包含的头文件中定义.例如:

#ifndef __INCLUDE_GUARD_HERE__
#define __INCLUDE_GUARD_HERE__

struct tt {
  int a;
  int b;
};

#endif
Run Code Online (Sandbox Code Playgroud)

现在两个.c文件都可以#include是头文件.