详解C语言中的宏定义

来源:互联网 发布:linux 卸载显卡驱动 编辑:程序博客网 时间:2024/05/18 00:59

1. 防止一个头文件被重复包含 

[cpp] view plain copy
 print?
  1. #ifndef COMDEF_H   
  2. #define COMDEF_H   
  3. //头文件内容   
  4. #endif   


2. 重新定义一些类型,防止由于各种平台和编译器的不同,而产生的类型字节数差异,方便移植。 
[cpp] view plain copy
 print?
  1. typedef  unsigned char      boolean;     /* Boolean value type. */   
  2. typedef  unsigned long int  uint32;      /* Unsigned 32 bit value */   
  3. typedef  unsigned short     uint16;      /* Unsigned 16 bit value */   
  4. typedef  unsigned char      uint8;       /* Unsigned 8  bit value */   
  5. typedef  signed long int    int32;       /* Signed 32 bit value */   
  6. typedef  signed short       int16;       /* Signed 16 bit value */   
  7. typedef  signed char        int8;        /* Signed 8  bit value */   


3. 得到指定地址上的一个字节或字 
[cpp] view plain copy
 print?
  1. #define  MEM_B( x )  ( *( (int8 *) (x) ) )   
  2. #define  MEM_W( x )  ( *( (uint16 *) (x) ) )   


4. 求最大值和最小值 
    会存在Duplication of Side Effects问题。这里的Side Effect是指宏在展开的时候对其参数可能进行多次Evaluation(也就是取值),但是如果这个宏参数是一个函数,那么就有可能被调用多次从而达到不一致的结果,甚至会发生更严重的错误。比如:
[cpp] view plain copy
 print?
  1. #define  MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )   
  2. #define  MIN( x, y ) ( ((x) < (y)) ? (x) : (y) )   
  3. c = min(a,foo(b));  
这时foo()函数就被调用了两次。为了解决这个潜在的问题,我们应当这样写min(X,Y)这个宏:
[cpp] view plain copy
 print?
  1. #define min(X,Y) ({\  
  2. typeof (X) x_ = (X);\  
  3. typeof (Y) y_ = (Y);\  
  4. (x_ < y_) ? x_ : y_; })  
({...})的作用是将内部的几条语句中最后一条的值返回,它也允许在内部声明变量(因为它通过大括号组成了一个局部Scope)

5,得到一个field在结构体(struct)中的偏移量 
[cpp] view plain copy
 print?
  1. #define FPOS( type, field ) ( (dword) &(( type *) 0)-> field )  

6,得到一个结构体中field所占用的字节数 
[cpp] view plain copy
 print?
  1. #define FSIZ( type, field ) sizeof( ((type *) 0)->field )   

7,按照LSB格式把两个字节转化为一个Word 
[cpp] view plain copy
 print?
  1. #define  FLIPW( ray ) ( (((word) (ray)[0]) * 256) + (ray)[1] )   

8,按照LSB格式把一个Word转化为两个字节 
[cpp] view plain copy
 print?
  1. #define<span style="white-space:pre">   </span>FLOPW( ray, val ) \   
  2. <span style="white-space:pre">  </span>(ray)[0] = ((val) / 256); \   
  3. <span style="white-space:pre">  </span>(ray)[1] = ((val) & 0xFF)   

9,得到一个变量的地址(word宽度) 
[cpp] view plain copy
 print?
  1. #define  B_PTR( var )  ( (int8 *) (void *) &(var) )   
  2. #define  W_PTR( var )  ( (uint16 *) (void *) &(var) )   

10,得到一个字的高位和低位字节 
[cpp] view plain copy
 print?
  1. #define  WORD_LO(xxx)  ((byte) ((uint16)(xxx) & 255))   
  2. #define  WORD_HI(xxx)  ((byte) ((uint16)(xxx) >> 8))   

11,返回一个比X大的最接近的8的倍数 
[cpp] view plain copy
 print?
  1. #define RND8( x )       ((((x) + 7) / 8 ) * 8 )   

12,将一个字母转换为大写 
[cpp] view plain copy
 print?
  1. #define  UPCASE( c ) ( ((c) >= ''a'' && (c) <= ''z'') ? ((c) - 0x20) : (c) )  

13,判断字符是不是10进值的数字 
[cpp] view plain copy
 print?
  1. #define  DECCHK( c ) ((c) >= ''0'' && (c) <= ''9'')   

14,判断字符是不是16进值的数字 
[cpp] view plain copy
 print?
  1. #define  HEXCHK( c ) ( ((c) >= ''0'' && (c) <= ''9'') ||\   
  2.                        ((c) >= ''A'' && (c) <= ''F'') ||\   
  3.                ((c) >= ''a'' && (c) <= ''f'') )   

15,防止溢出的一个方法 
[cpp] view plain copy
 print?
  1. #define  INC_SAT( val )  (val = ((val)+1 > (val)) ? (val)+1 : (val))   

16,返回数组元素的个数 
[cpp] view plain copy
 print?
  1. #define  ARR_SIZE( a )  ( sizeof( (a) ) / sizeof( (a[0]) ) )   

17,返回一个无符号数n尾的值

MOD_BY_POWER_OF_TWO(X,n)=X%(2^n) 

[cpp] view plain copy
 print?
  1. #define MOD_BY_POWER_OF_TWO( val, mod_by ) \   
  2.            ( (dword)(val) & (dword)((mod_by)-1) )   

18,对于IO空间映射在存储空间的结构,输入输出处理 
[cpp] view plain copy
 print?
  1. #define inp(port)         (*((volatile byte *) (port)))   
  2. #define inpw(port)        (*((volatile word *) (port)))   
  3. #define inpdw(port)       (*((volatile dword *)(port)))   
  4. #define outp(port, val)   (*((volatile byte *) (port)) = ((byte) (val)))   
  5. #define outpw(port, val)  (*((volatile word *) (port)) = ((word) (val)))   
  6. #define outpdw(port, val) (*((volatile dword *) (port)) = ((dword) (val)))   


19. 使用一些宏跟踪调试 
ANSI标准说明了五个预定义的宏名。它们是: 
_LINE_
_FILE_ 
_DATE_ 
_TIME_ 
_STDC_ 
如果编译不是标准的,则可能仅支持以上宏名中的几个,或根本不支持。记住编译程序也许还提供其它预定义的宏名。 
_LINE_标识当前代码所在的行号
_FILE_标识代码所在的文件名
_DATE_宏指令含有形式为月/日/年的串,表示源文件被翻译到代码时的日期。 
源代码翻译到目标代码的时间作为串包含在_TIME_中。串形式为时:分:秒。 
如果实现是标准的,则宏_STDC_含有十进制常量1。如果它含有任何其它数,则实现是非标准的。 

可以定义宏,例如: 
当定义了_DEBUG,输出数据信息和所在文件所在行 
[cpp] view plain copy
 print?
  1. #ifdef _DEBUG   
  2. #define DEBUGMSG(msg,date) printf(msg);printf(“%d%d%d”,date,_LINE_,_FILE_)   
  3. #else   
  4. #define DEBUGMSG(msg,date)   
  5. #endif   

20. 宏定义防止使用是错误用小括号包含。 
例如:

[cpp] view plain copy
 print?
  1. #define ADD(a,b) (a+b)   
用do{}while(0)语句包含多语句防止错误 
例如:
[cpp] view plain copy
 print?
  1. #difne DO(a,b) a+b; a++;   
应用时:
[cpp] view plain copy
 print?
  1. if(...)   
  2. DO(a,b); //产生错误   
  3. else   
  4. ...  
解决方法: 
[cpp] view plain copy
 print?
  1. #define DO(a,b) do{a+b;a++;}while(0)   

21. 宏中"#"和"##"的用法
#的功能是将其后面的宏参数进行字符串化操作(Stringfication)。
##被称为连接符(concatenator),用来将两个Token连接为一个Token。注意这里连接的对象是Token就行,而不一定是宏的变量。
用法: 
[cpp] view plain copy
 print?
  1. #include<cstdio>   
  2. #include<climits>   
  3. using namespace std;   
  4.   
  5. #define STR(s)     #s   
  6. #define CONS(a,b)  int(a##e##b)   
  7.   
  8. int main()   
  9. {   
  10.     printf(STR(vck));           // 输出字符串"vck"   
  11.     printf("%d\n", CONS(2,3));  // 2e3 输出:2000   
  12.     return 0;   
  13. }   

当宏参数是另一个宏的时候,需要注意的是凡宏定义里有用''#''或''##''的地方宏参数是不会再展开. 
1) 非''#''和''##''的情况 
[cpp] view plain copy
 print?
  1. #define TOW      (2)   
  2. #define MUL(a,b) (a*b)   
  3. printf("%d*%d=%d\n", TOW, TOW, MUL(TOW,TOW));   
这行的宏会被展开为: 
[cpp] view plain copy
 print?
  1. printf("%d*%d=%d\n", (2), (2), ((2)*(2)));   
MUL里的参数TOW会被展开为(2). 

2) 当有''#''或''##''的时候 
[cpp] view plain copy
 print?
  1. #define A          (2)   
  2. #define STR(s)     #s   
  3. #define CONS(a,b)  int(a##e##b)   
  4. printf("int max: %s\n",  STR(INT_MAX));    // INT_MAX #include<climits>   
这行会被展开为: 
[cpp] view plain copy
 print?
  1. printf("int max: %s\n""INT_MAX");   
[cpp] view plain copy
 print?
  1. printf("%s\n", CONS(A, A));               // compile error    
这一行则是: 
[cpp] view plain copy
 print?
  1. printf("%s\n"int(AeA));   
INT_MAX和A都不会再被展开, 然而解决这个问题的方法很简单. 加多一层中间转换宏. 
加这层宏的用意是把所有宏的参数在这层里全部展开, 那么在转换宏里的那一个宏(_STR)就能得到正确的宏参数. 
[cpp] view plain copy
 print?
  1. #define A           (2)   
  2. #define _STR(s)     #s   
  3. #define STR(s)      _STR(s)          // 转换宏   
  4. #define _CONS(a,b)  int(a##e##b)   
  5. #define CONS(a,b)   _CONS(a,b)       // 转换宏   
  6.   
  7. printf("int max: %s\n", STR(INT_MAX));          // INT_MAX,int型的最大值,为一个变量 #include<climits>   
输出为: int max: 0x7fffffff 
STR(INT_MAX) -->  _STR(0x7fffffff) 然后再转换成字符串; 
[cpp] view plain copy
 print?
  1. printf("%d\n", CONS(A, A));   
输出为:200 
CONS(A, A)  -->  _CONS((2), (2))  --> int((2)e(2)) 

3)''#''和''##''的一些应用特例 
i) 合并匿名变量名 
[cpp] view plain copy
 print?
  1. #define  ___ANONYMOUS1(type, var, line)  type  var##line   
  2. #define  __ANONYMOUS0(type, line)  ___ANONYMOUS1(type, _anonymous, line)   
  3. #define  ANONYMOUS(type)  __ANONYMOUS0(type, __LINE__)   
例:ANONYMOUS(static int);  即: static int _anonymous70;  70表示该行行号; 
第一层:ANONYMOUS(static int);  -->  __ANONYMOUS0(static int, __LINE__); 
第二层:                        -->  ___ANONYMOUS1(static int, _anonymous, 70); 
第三层:                        -->  static int  _anonymous70; 
即每次只能解开当前层的宏,所以__LINE__在第二层才能被解开; 

ii) 填充结构 
比如你要做一个菜单项命令名和函数指针组成的结构体的数组,并且希望在函数名和菜单项命令名之间有直观的、名字上的关系。那么下面的代码就非常实用:
[cpp] view plain copy
 print?
  1. struct command  
  2. {  
  3. <span style="white-space:pre">  </span>char * name;  
  4. <span style="white-space:pre">  </span>void (*function) (void);  
  5. };  
  6. #define COMMAND(NAME) { NAME, NAME##_command }  
然后你就用一些预先定义好的命令来方便的初始化一个command结构的数组了:
[cpp] view plain copy
 print?
  1. struct command commands[] = {  
  2. COMMAND(quit),  
  3. COMMAND(help),  
  4. ...  
  5. }  
COMMAND宏在这里充当一个代码生成器的作用,这样可以在一定程度上减少代码密度,间接地也可以减少不留心所造成的错误。

再比如:
[cpp] view plain copy
 print?
  1. #define  FILL(a)   {a, #a}   
  2.   
  3. enum IDD{OPEN, CLOSE};   
  4. typedef struct MSG{   
  5. <span style="white-space:pre">  </span>IDD id;   
  6. <span style="white-space:pre">  </span>const char * msg;   
  7. }MSG;   
  8.   
  9. MSG _msg[] = {FILL(OPEN), FILL(CLOSE)};   
相当于: 
[cpp] view plain copy
 print?
  1. MSG _msg[] = {{OPEN, "OPEN"},   
  2.               {CLOSE, "CLOSE"}};  

iii) 记录文件名 
[cpp] view plain copy
 print?
  1. #define  _GET_FILE_NAME(f)   #f   
  2. #define  GET_FILE_NAME(f)    _GET_FILE_NAME(f)   
  3. static char  FILE_NAME[] = GET_FILE_NAME(__FILE__);   

iv) 得到一个数值类型所对应的字符串缓冲大小 
[cpp] view plain copy
 print?
  1. #define  _TYPE_BUF_SIZE(type)  sizeof #type   
  2. #define  TYPE_BUF_SIZE(type)   _TYPE_BUF_SIZE(type)  
char  buf[TYPE_BUF_SIZE(INT_MAX)]; 
     -->  char  buf[_TYPE_BUF_SIZE(0x7fffffff)]; 
     -->  char  buf[sizeof "0x7fffffff"]; 
这里相当于: 
char  buf[11]; 

22. 关于...的使用
...在C宏中称为Variadic Macro,也就是变参宏。比如:
[cpp] view plain copy
 print?
  1. #define myprintf(templt,...) fprintf(stderr,templt,__VA_ARGS__)  
或者
[cpp] view plain copy
 print?
  1. #define myprintf(templt,args...) fprintf(stderr,templt,args)  
第一个宏中由于没有对变参起名,我们用默认的宏__VA_ARGS__来替代它。第二个宏中,我们显式地命名变参为args,那么我们在宏定义中就可以用 args来代指变参了。
同C语言的stdcall一样,变参必须作为参数表的最有一项出现。当上面的宏中我们只能提供第一个参数templt时,C标准要求我们必须写成:
[cpp] view plain copy
 print?
  1. myprintf(templt,);  
的形式。这时的替换过程为:
[cpp] view plain copy
 print?
  1. myprintf("Error! ",);  
替换为:
[cpp] view plain copy
 print?
  1. fprintf(stderr,"Error! ",);  
这是一个语法错误,不能正常编译。
这个问题一般有两个解决方法。首先,GNU CPP提供的解决方法允许上面的宏调用写成:
[cpp] view plain copy
 print?
  1. myprintf(templt);  
而它将会被通过替换变成:
[cpp] view plain copy
 print?
  1. fprintf(stderr,"Error! ",);  
很明显,这里仍然会产生编译错误(非本例的某些情况下不会产生编译错误)。
除了这种方式外,c99和GNU CPP都支持下面的宏定义方式:
[cpp] view plain copy
 print?
  1. #define myprintf(templt, ...) fprintf(stderr,templt, ##__VAR_ARGS__)  
这时,##这个连接符号充当的作用就是当__VAR_ARGS__为空的时候,消除前面的那个逗号。那么此时的翻译过程如下:
[cpp] view plain copy
 print?
  1. myprintf(templt);  
被转化为:
[cpp] view plain copy
 print?
  1. fprintf(stderr,templt);  
这样如果templt合法,将不会产生编译错误。

23.错误的嵌套Misnesting
宏的定义不一定要有完整的、配对的括号,但是为了避免出错并且提高可读性,最好避免这样使用。

24.由操作符优先级引起的问题-Operator Precedence Problem
由于宏只是简单的替换,宏的参数如果是复合结构,那么通过替换之后可能由于各个参数之间的操作符优先级高于单个参数内部各部分之间相互作用的操作符优先级,如果我们不用括号保护各个宏参数,可能会产生预想不到的情形。
比如:
[cpp] view plain copy
 print?
  1. #define ceil_div(x, y) (x + y - 1) / y  
那么
[cpp] view plain copy
 print?
  1. a = ceil_div( b & c, sizeof(int) );  
将被转化为:
[cpp] view plain copy
 print?
  1. a = ( b & c   + sizeof(int) - 1) / sizeof(int);  
由于+/-的优先级高于&的优先级,那么上面式子等同于:
[cpp] view plain copy
 print?
  1. a = ( b & (c + sizeof(int) - 1)) / sizeof(int);  
这显然不是调用者的初衷。为了避免这种情况发生,应当多写几个括号:
[cpp] view plain copy
 print?
  1. #define ceil_div(x, y) (((x) + (y) - 1) / (y))  

25.消除多余的分号-Semicolon Swallowing
通常情况下,为了使函数模样的宏在表面上看起来像一个通常的C语言调用一样,通常情况下我们在宏的后面加上一个分号,比如下面的带参宏:
[cpp] view plain copy
 print?
  1. MY_MACRO(x);  
但是如果是下面的情况:
[cpp] view plain copy
 print?
  1. #define MY_MACRO(x) {\  
  2. /* line 1 */\  
  3. /* line 2 */\  
  4. /* line 3 */ }  
  5.   
  6. if (condition())  
  7. MY_MACRO(a);  
  8. else  
  9. {...}  
这样会由于多出的那个分号产生编译错误。为了避免这种情况出现同时保持MY_MACRO(x);的这种写法,我们需要把宏定义为这种形式:
[cpp] view plain copy
 print?
  1. #define MY_MACRO(x) do {\  
  2. /* line 1 */\  
  3. /* line 2 */\  
  4. /* line 3 */ } while(0)  
这样只要保证总是使用分号,就不会有任何问题。
0 0