C++预处理命令之文件包含和条件编译

文件包含的命令#include有俩种形式:

1、#include <头文件名>

2、#include “头文件名” 

1、文件包含路径问题

文件包含头文件绝对路径:

#include “C:\DEV\GSL\include\gsl_linalg.h”
#include<C:DEV\SDL\include\SDL.h>


文件包含头文件相对路径:


#include<math.h>
#include<zlib\zlib.h>
#include”user.h”
#include“share\a.h”

文件包含命令是相对系统include路径和用户路径来查找头文件的(用户路径就是我们创建项目的路径)

#include”user.h”
//user.h  在C:\DEV\MinGW\include
#include“share\a.h”
//a.h在C:\DEV\MinGW\include\share

假设用户路径为D:\Devshop:

#include”user.h”
//user.h  在D:\Devshop或者C:\DEV\MinGW\include
#include“share\a.h”
//a.h在D:\Devshop\share或者C:\DEV\MinGW\include\share

2、文件包含的重复包含问题

头文件优势需要避免重复包含,例如一些特定的声明不能多次声明,而且重复包含增加了变异事件。这时可以采用以下俩个办法之一。

  1. 使用条件编译
  2. 使用特殊预处理命令#pragma

1、#ifdeft条件编译命令

测试条件字段是否定义,以此选择参与编译的程序代码段,他有俩种命令形式。

  1. 第一种形式:
#ifdef 条件字段

……程序代码段1

#endif

    2、第二种形式:

#ifdef 条件字段
……程序代码段1
#else
……//程序代码段2
#endif

例如:如果DEBUG已经定义编译printf语句,否则不编译;

#ifdef 条件字段

Printf(“x=%d,y=%d,z=%d\n”,x,y,z)

#endif
#include <iostream>
using namespace std;
int main()
{
double sn=100.o,hn=sn/2;
int n;
for(n=2;n<=10;n++){
sn=sn+2*hn;
hn=hn/2;
#ifdef _DEBUG
count<<”sn=”<<sn<<”,hn=”<<hn<<endl;
#endif
}
count<<”the  total  of  road  is “<<sn<<endl;
count<<the tenth is “<<hn<<” meter”<<endl
return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值