为什么头文件中都有 #ifndefine #define #endif

54 篇文章 1 订阅

许多人都知道,下面的语句把.h文件包括起来,目的是为了避免重复包含:
#ifndef   _my_head_file_h
#define   _my_head_file_h
...
...
...
#endif

问题是:头文件一般都是变量、函数的声明,重复声明并没有问题啊!
例1:
typedef   void   myfunction();
typedef   void   myfunction();

例2:
#define   DDD   2
#define   DDD   2

以上两例出现在同一个.cpp文件中,vc编译器通过编译。这是不是说,就算是头文件的重复包含,也不会引起编译错误?

原因:

 声明是可以重复的,但.h   文件中不只有声明,还有可能有定义,比如最常见的class定义,和const定义,这些都不能重复地出现在同一个编译单位中。

如:

#include <stdio.h>
#define d 3
#define d 3
 struct student{
 int a;
 int b;};
  struct student{
 int a;
 int b;};

void main()
{
  struct student a;


}


错误提示:

--------------------Configuration: t - Win32 Debug--------------------
Compiling...
t.c
C:\Documents and Settings\Administrator\t.c(7) : error C2011: 'student' : 'struct' type redefinition
Error executing cl.exe.

t.exe - 1 error(s), 0 warning(s)

 

错误提示

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值