c - 为什么我的结构(在头文件中声明)在 gcc 编译的 c 文件中无法被识别?

标签 c struct header-files

我无法编译以下代码,因为我的 gcc 编译器 (MSYS2 12.1.0) 无法识别我在头文件 diffDates.h 中创建的结构。

下面是头文件

#ifndef DIFFDates_H
#define DIFFDates_H

int getDifference(Date dt1, Date dt2);

// A date has day 'd', month 'm' and year 'y'
struct Date {
    int d, m, y;
};

#endif

下面是我的主文件 makefiles.c

#include <stdio.h>
#include <string.h>
#include "diffDates.h"

int main()
{
    char str_start[10];
    char str_end[10];
    printf("Please enter the start date in dd.mm.yy: ");
    scanf("%s", str_start);
    printf("\nPlease enter the end date in dd.mm.yy:");
    scanf("%s", str_end);

    return 0;
}

下面是 GCC 编译器的输出

gcc makefiles.c -o makefiles     
In file included from makefiles.c:7:
diffDates.h:4:19: error: unknown type name 'Date'
    4 | int getDifference(Date dt1, Date dt2);
      |                   ^~~~
diffDates.h:4:29: error: unknown type name 'Date'
    4 | int getDifference(Date dt1, Date dt2);
      |                             ^~~~
diffDates.h:19:20: error: unknown type name 'Date'
   19 | int countLeapYears(Date d)
      |                    ^~~~
diffDates.h:40:19: error: unknown type name 'Date'
   40 | int getDifference(Date dt1, Date dt2)
      |                   ^~~~
diffDates.h:40:29: error: unknown type name 'Date'
   40 | int getDifference(Date dt1, Date dt2)
      |    

我想知道出了什么问题,因为我可以在主文件中包含函数,但由于某种原因未定义结构。

最佳答案

首先,在C中。要定义一个结构并声明该结构的实例,您可以键入:

struct Date {
    int d, m, y;
};

int getDifference(struct Date dt1, struct Date dt2);

或者

typedef struct Date {
    int d, m, y;
}Date;

int getDifference(Date dt1, Date dt2);

第二行:

int getDifference(Date dt1, Date dt2);

必须在:

之后
typedef struct Date {
    int d, m, y;
}Date;

不是在它之前,就像在编译期间一样。当编译器到达该行 int getDifference(Date dt1, Date dt2); 时,它没有有关名为 Date 的用户数据类型的信息。

因此将头文件编辑为:

#ifndef DIFFDates_H
#define DIFFDates_H

// A date has day 'd', month 'm' and year 'y'
typedef struct Date {
    int d, m, y;
}Date;

int getDifference(Date dt1, Date dt2);

#endif

关于c - 为什么我的结构(在头文件中声明)在 gcc 编译的 c 文件中无法被识别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73955094/

相关文章:

c++ - 将 vector 结构写入C++中的二进制文件

c - 释放结构体指针的内存

c++ - header 导入并包含 XCode、cmath、objc-class.h 等中的失败

c++ - 在 header 或 cpp 中包含标准库?

c - 如何调用参数数量可变的函数?

c - 如果字符为 null,则打印 null

c++ - 指向结构的指针 vector

导致框架崩溃的代码,但在单个文件中重现时,它起作用了

c++ - LIBUSB编译错误

c - 如何修复 "implicit declaration of function"