Free mind

Be fresh and eager every morning, and tired and satisfied every night.
posts - 39, comments - 2, trackbacks - 0, articles - 0
   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

预处理器

Posted on 2007-05-30 09:56 morphis 阅读(237) 评论(0)  编辑  收藏 所属分类: 1. C/Cpp

预处理器

 

预处理器在编译器之前根据指令更改程序文本。编译器看到的是预处理器修改的代文本(称作“翻译单元(translation unit)”)。

 

预处理器的三大功能:

1文件或源文件包含;

2。宏展;

3。条件编译

 

文件包含:

#include <stdio.h>         //编译器首先到文件库查找;

#include “myHead.h”     //编译器首先到当前目找,如找不到再到文件库查找;

 

预处理指令:

#include  #define  #undef  #if  #elif  #else  #endif  #ifdef  #ifndef  #error  #line  #pragma

 

宏定

#define一个宏;用#undef除一个宏;

 

宏的分

无参数宏(类对象宏)

例:

#define MAXLINES 500

类对象宏似常数,因此可以用下面句代替,并且推荐用下面句来定

Const int MAXLINES = 500;

 

       参数宏(函数宏)

例:

#define abs(x)  ( (x) > 0 ? (x) : (- (x) ) )          

//参数最好用括号封装,这样在替换时不会生歧

函数宏大多可以用内函数来代替,并且推荐。

inline int abs(int x)

{

       return x > 0 ? x : (-x);

}

 

宏:

__LINE__  __FILE__  __DATE__  __TIME__  __cplusplus

 

例:

// sysmac.cpp

#include <iostram>

using namespace std;

main()

{

       Cout << “__DATE__ == “ << __DATE__ << endl;

       Cout << “__TIME__ == “ << __TIME__ << endl;

       Cout << “__LINE__ == “ << __LINE__ << endl;

       Cout << “__FILE__ == “ << __FILE__ << endl;

}

//出:

__DATE__ == Nov 28 1996

__TIME__ == 09:37:38

__LINE__ == 7

__FILE__ == sysmac.cpp

 

预处理运算符:

#  ##  Defined

# 字符串化;## 标记

具体看下面的例子:

#include <stdio.h>

 

#define trace(x,format)  printf(#x  “= %”  #format  “\n” , x)

#define trace2(i)  trace(x  ## i , d)

 

main()

{

       int i = 1;

float x = 2.0;

char *s = “three”;

 

trace(i,d);                     //printf( “x” “=%” “d” “\n” , x)

trace(x,f);

trace(s,s);

 

Int x1=1,x2=2,x3=3;

 

trace2(1);                     //trace(x1,d)

trace2(2);

trace2(3);

}

//出:

i = 1

x = 2.000000

s = three

x1 = 1

x2 = 2

x3 = 3

 


只有注册用户登录后才能发表评论。


网站导航: