头文件包含另一个头文件生成重新定义

header file include another header file generate redefinition

头文件是否不能在 C 中包含另一个头文件?

我从Nuvoton网站下载代码,对于Keil C51项目,使用UART示例代码,只需添加文件"EasyTransfer.h"并包含"Typedef.h",结果显示如下大量错误信息。

\N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(1): error C231: 'BIT': 重定义 \N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(2): error C231: 'UINT8': 重定义 \N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(3): error C231: 'UINT16': 重定义 \N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(4):错误 C141:'UINT32' 附近的语法错误 \N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(6): error C231: 'uint8_t': 重定义 \N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(7): error C231: 'uint16_t': 重定义 \N79E85x_Sample_Code_V1.0.8(1)\Include\Typedef.h(8):错误 C141:'uint32_t'

附近的语法错误

"EasyTransfer.h"很简单,就几行

#ifndef EasyTransfer_h
#define EasyTransfer_h
#include "Typedef.h"
uint8_t * address;  //address of struct    
#endif

以下是主要代码和source link,我认为这可能有助于理解我的问题。

#define Uart_Port_Sel   0x00

#include <stdio.h>
#include "N79E85x.h"
#include "Typedef.h"
#include "Define.h"
#include "Common.h"
#include "Delay.h"
#include "Version.h"
#include "EasyTransfer.h"
UINT8 u8Uart_Data;

//-----------------------------------------------------------------------------------------------------------
void main (void)
{
    AUXR1 |= Uart_Port_Sel;             // Select P10/P11 as UART pin(default)

    InitialUART0_Timer1(9600);          // 9600 Baud Rate @ 11.0592MHz
    Show_Version_Number_To_PC();
    ES = 1;                             // Enable serial interrupt
    EA = 1;                             // Enable global interrupt

    while(1);                           // Endless
}
//-----------------------------------------------------------------------------------------------------------
void UART_ISR(void) interrupt 4
{
    if (RI == 1)
    {                                   // If reception occur
        RI = 1;                         // Clear reception flag for next reception
        u8Uart_Data = SBUF;             // Read receive data
        SBUF = u8Uart_Data;             // Send back same data on UART
    }
    else TI = 0;                        // If emission occur
                                        // Clear emission flag for next emission
}

您不应多次包含 Typedef.h,因为 Typedef.h 中没有 header 包含守卫。

您的主要来源同时包含 Typedef.h 和 EasyTransfer.h,这会导致重新定义错误,因为 EasyTransfer.h 也包含 Typedef.h。就像您的主要来源包含 Typedef.h 两次,并且没有 header 包含 guard!

我建议您只从主源文件中删除#include "Typedef.h" 行。或者如果可以的话,在 Typedef.h 中添加 header include guard。