【问题标题】:Header File Doesn't Recognize typedef from a Different Header File头文件无法识别来自不同头文件的 typedef
【发布时间】:2016-05-03 10:27:54
【问题描述】:

现在我正在为我的系统编程课程做一个项目。我们被要求与房地产经纪人和客户一起设计一个公寓销售平台。我正在开发 Eclipse。

现在,即使我过去没有遇到任何类似的问题,但我的一个头文件无法从第二个头文件中识别 typedef。

说明:这是我的文件;

房地产经纪人.h

#include "apartment.h"
#include "apartment_service.h"
#include "Report.h"
#include "Customer.h"
#include "mtm_ex2.h"


typedef struct realtor_t* Realtor;

虽然这是第二个头文件;

客户.h

#include "Report.h"
#include "Realtor.h"
#include "apartment.h"
#include "apartment_service.h"
#include "mtm_ex2.h"

typedef struct customer_t* Customer;

MtmErrorCode purchaseApartment (Customer customer, Realtor realtor,
        ApartmentService service,
        int apartment_id);

MtmErrorCode makeOffer (Customer customer, Realtor realtor, ApartmentService
        service, int apartment_id, int new_price);

(customer_t和realtor_t的结构体在源文件中定义)

出于某种原因,Customer.h 中的函数声明给了我以下错误:“未知类型名称'Realtor'”。这真的很奇怪,因为相同的函数使用其他类型定义,例如“apartment_service.h”中的“ApartmentService”。

【问题讨论】:

  • 我缺少一些包含保护,因为您的标题中有循环包含。你有这些守卫,只是为了解决这些第一个错误。
  • 补充一点:即使有警卫,Customer.h 也包括Realtor.h,其中包括Customer.h,其中包括(可能有警卫)Realtor.h。如果没有包括警卫,这根本不起作用。使用 include 守卫,Realtor.h 的第二个 include 刚刚通过,您最终在 Customer.h 没有任何 Realtor.h 声明(因为您实际上正在处理该 include)。

标签: c eclipse typedef


【解决方案1】:

您将 Customer.h 包含在 Realtor.h 中。

这是发生错误的地方。在 Realtor.h 中,Realtor 的 typedef 未在 Customer.h 之前定义

从 Realtor.h 中删除包含 Customer.h。这应该可以解决给定代码的问题。

【讨论】:

  • 不幸的是,这没有帮助。也许还有更多想法?非常感谢!
【解决方案2】:

您根本不应该这样做。您应该在代码文件中包含这些包含文件,而不是包含文件。

在你的头文件中有typedef struct customer_t* Customer; 这样的声明很好。当您定义指向某种类型的指针时,您不需要这样的声明来了解更多信息。这就是编译器需要知道的所有原型。

编辑

每个模块应该只导出它提供的内容,并且总应该“建立”所以最好没有循环依赖。例如,Apartment 是一个基“类”,Apartment Services 使用 Apartment;客户是一个基“类”,您的程序具有客户购买公寓的功能。有时无法防止循环引用或前向引用。在这种情况下,您应该使用“包含保护”来确保包含文件的内容只包含一次。

/* apartment.h */
#ifndef APT_INCLUDED
#define APT_INCLUDED
typedef struct Apartment* tApartmemt;
tApartment NewApartment(char * name);
#endif /*APT_INCLUDED*/

/* apartment_services.h */
#ifndef APTSVC_INCLUDED
#define APTSVC_INCLUDED
#include "apartment.h"
typedef struct ApartmentService* tAptSvc;
tAptSvc NewAptSvc(tApartment apartment, char *svcname);
#endif /*APTSVC_INCLUDED*/

仔细看看谁需要知道什么也可以简化您的包含结构,例如,我怀疑 makeOffer 应该是客户模块的一部分,因此该模块不需要包含公寓或房地产经纪人;相反,提供报价的是房地产经纪人。我还注意到您的包含似乎有点随机顺序。无论如何,使用包含防护可以防止循环包含,并且应该可以解决您原来的问题。我希望这会有所帮助。

【讨论】:

  • 那么我应该如何在我的 .h 文件中做函数声明呢?例如,我试图在那里声明的函数使用来自 ApartmentService.h 的 ApartmentService 和来自 Realtor.h 的 Realtor。如果我不将它们包含在我的 .h 中,我如何在我的函数声明中使用它们?非常感谢!
【解决方案3】:

Realtor.h 头文件中将 typedef struct realtor_t* Realtor; 行放在 Customer.h 的包含之前。

【讨论】:

    猜你喜欢
    • 2015-11-13
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多