查看完整版本: C语言宏定义使用技巧

CPP 2008-10-1 20:05

C语言宏定义使用技巧

[size=2]写好[font=\"times\"]C[/font]语言,漂亮的宏定义很重要,使用宏定义可以防止出错,提高可移植性,可读性,方便性[font=\"times\"] [/font]等等。下面列举一些成熟软件中常用得宏定义。。。。。。
[font=\"times\"]1[/font],防止一个头文件被重复包含[/size]
[size=2][font=\"times\"]#ifndef COMDEF_H[/font][/size]
[size=2][font=\"times\"]#define COMDEF_H[/font][/size]
[size=2][font=\"times\"]//[/font]头文件内容[/size]
[size=2][font=\"times\"]#endif[/font][/size]
[size=2][font=\"times\"]2[/font],重新定义一些类型,防止由于各种平台和编译器的不同,而产生的类型字节数差异,方便移植。[/size]
[size=2][font=\"times\"]typedef unsigned char boolean; /* Boolean value type. */[/font][/size]
[size=2][font=\"times\"]typedef unsigned long int uint32; /* Unsigned 32 bit value */[/font][/size]
[size=2][font=\"times\"]typedef unsigned short uint16; /* Unsigned 16 bit value */[/font][/size]
[size=2][font=\"times\"]typedef unsigned char uint8; /* Unsigned 8 bit value */[/font][/size]
[size=2][font=\"times\"]typedef signed long int int32; /* Signed 32 bit value */[/font][/size]
[size=2][font=\"times\"]typedef signed short int16; /* Signed 16 bit value */[/font][/size]
[size=2][font=\"times\"]typedef signed char int8; /* Signed 8 bit value */[/font][/size]
[size=2][font=\"times\"]//[/font]下面的不建议使用[/size]
[size=2][font=\"times\"]typedef unsigned char byte; /* Unsigned 8 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef unsigned short word; /* Unsinged 16 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef unsigned long dword; /* Unsigned 32 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef unsigned char uint1; /* Unsigned 8 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef unsigned short uint2; /* Unsigned 16 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef unsigned long uint4; /* Unsigned 32 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef signed char int1; /* Signed 8 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef signed short int2; /* Signed 16 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef long int int4; /* Signed 32 bit value type. */[/font][/size]
[size=2][font=\"times\"]typedef signed long sint31; /* Signed 32 bit value */[/font][/size]
[size=2][font=\"times\"]typedef signed short sint15; /* Signed 16 bit value */[/font][/size]
[size=2][font=\"times\"]typedef signed char sint7; /* Signed 8 bit value */[/font][/size]
[size=2][font=\"times\"]3[/font],得到指定地址上的一个字节或字[/size]
[size=2][font=\"times\"]#define MEM_B( x ) ( *( (byte *) (x) ) )[/font][/size]
[size=2][font=\"times\"]#define MEM_W( x ) ( *( (word *) (x) ) )[/font][/size]
[size=2][font=\"times\"]4[/font],求最大值和最小值[/size]
[size=2][font=\"times\"]#define MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )[/font][/size]
[size=2][font=\"times\"]#define MIN( x, y ) ( ((x) < (y)) ? (x) : (y) )[/font][/size]
[size=2][font=\"times\"]5[/font],得到一个[font=\"times\"]field[/font]在结构体[font=\"times\"](struct)[/font]中的偏移量[/size]
[size=2][font=\"times\"]#define FPOS( type, field ) \[/font][/size]
[size=2][font=\"times\"]/*lint -e545 */ ( (dword) &(( type *) 0)-> field ) /*lint +e545 */[/font][/size]
[size=2][font=\"times\"]6,[/font]得到一个结构体中[font=\"times\"]field[/font]所占用的字节数[/size]
[size=2][font=\"times\"]#define FSIZ( type, field ) sizeof( ((type *) 0)->field )[/font][/size]
[size=2][font=\"times\"]7[/font],按照[font=\"times\"]LSB[/font]格式把两个字节转化为一个[font=\"times\"]Word[/font][/size]
[size=2][font=\"times\"]#define FLIPW( ray ) ( (((word) (ray)[0]) * 256) + (ray)[1] )[/font][/size]
[size=2][font=\"times\"]8[/font],按照[font=\"times\"]LSB[/font]格式把一个[font=\"times\"]Word[/font]转化为两个字节[/size]
[size=2][font=\"times\"]#define FLOPW( ray, val ) \[/font][/size]
[size=2][font=\"times\"](ray)[0] = ((val) / 256); \[/font][/size]
[size=2][font=\"times\"](ray)[1] = ((val) & 0xFF)[/font][/size]
[size=2][font=\"times\"]9[/font],得到一个变量的地址([font=\"times\"]word[/font]宽度)[/size]
[size=2][font=\"times\"]#define B_PTR( var ) ( (byte *) (void *) &(var) )[/font][/size]
[size=2][font=\"times\"]#define W_PTR( var ) ( (word *) (void *) &(var) )[/font][/size]
[size=2][font=\"times\"]10[/font],得到一个字的高位和低位字节[/size]
[size=2][font=\"times\"]#define WORD_LO(***) ((byte) ((word)(***) & 255))[/font][/size]
[size=2][font=\"times\"]#define WORD_HI(***) ((byte) ((word)(***) >> 8))[/font][/size]
[size=2][font=\"times\"]11[/font],返回一个比[font=\"times\"]X[/font]大的最接近的[font=\"times\"]8[/font]的倍数[/size]
[size=2][font=\"times\"]#define RND8( x ) ((((x) + 7) / 8 ) * 8 )[/font][/size]
[size=2][font=\"times\"]12[/font],将一个字母转换为大写[/size]
[size=2][font=\"times\"]#define UPCASE( c ) ( ((c) >= 'a' && (c) <= 'z') ? ((c) - 0x20) : (c) )[/font][/size]
[size=2][font=\"times\"]13[/font],判断字符是不是[font=\"times\"]10[/font]进值的数字[/size]
[size=2][font=\"times\"]#define DECCHK( c ) ((c) >= '0' && (c) <= '9')[/font][/size]
[size=2][font=\"times\"]14[/font],判断字符是不是[font=\"times\"]16[/font]进值的数字[/size]
[size=2][font=\"times\"]#define HEXCHK( c ) ( ((c) >= '0' && (c) <= '9') ||\[/font][/size]
[size=2][font=\"times\"]((c) >= 'A' && (c) <= 'F') ||\[/font][/size]
[size=2][font=\"times\"]((c) >= 'a' && (c) <= 'f') )[/font][/size]
[size=2][font=\"times\"]15[/font],防止溢出的一个方法[/size]
[size=2][font=\"times\"]#define INC_SAT( val ) (val = ((val)+1 > (val)) ? (val)+1 : (val))[/font][/size]
[size=2][font=\"times\"]16[/font],返回数组元素的个数[/size]
[size=2][font=\"times\"]#define ARR_SIZE( a ) ( sizeof( (a) ) / sizeof( (a[0]) ) )[/font][/size]
[size=2][font=\"times\"]17[/font],返回一个无符号数[font=\"times\"]n[/font]尾的值[font=\"times\"]MOD_BY_POWER_OF_TWO(X,n)=X%(2^n)[/font][/size]
[size=2][font=\"times\"]#define MOD_BY_POWER_OF_TWO( val, mod_by ) \[/font][/size]
[size=2][font=\"times\"]( (dword)(val) & (dword)((mod_by)-1) )[/font][/size]
[size=2][font=\"times\"]18[/font],对于[font=\"times\"]IO[/font]空间映射在存储空间的结构,输入输出处理[/size]
[size=2][font=\"times\"]#define inp(port) (*((volatile byte *) (port)))[/font][/size]
[size=2][font=\"times\"]#define inpw(port) (*((volatile word *) (port)))[/font][/size]
[size=2][font=\"times\"]#define inpdw(port) (*((volatile dword *)(port)))[/font][/size]
[size=2][font=\"times\"]#define outp(port, val) (*((volatile byte *) (port)) = ((byte) (val)))[/font][/size]
[size=2][font=\"times\"]#define outpw(port, val) (*((volatile word *) (port)) = ((word) (val)))[/font][/size]
[size=2][font=\"times\"]#define outpdw(port, val) (*((volatile dword *) (port)) = ((dword) (val)))[/font][/size]
[size=2][font=\"times\"][2005-9-9[/font]添加[font=\"times\"]][/font][/size]
[size=2][font=\"times\"]19,[/font]使用一些宏跟踪调试[/size]
[size=2][font=\"times\"]A N S I[/font]标准说明了五个预定义的宏名。它们是:[/size]
[size=2][font=\"times\"]_ L I N E _[/font][/size]
[size=2][font=\"times\"]_ F I L E _[/font][/size]
[size=2][font=\"times\"]_ D A T E _[/font][/size]
[size=2][font=\"times\"]_ T I M E _[/font][/size]
[size=2][font=\"times\"]_ S T D C _[/font][/size]
[size=2]如果编译不是标准的,则可能仅支持以上宏名中的几个,或根本不支持。记住编译程序[/size]
[size=2]也许还提供其它预定义的宏名。[/size]
[size=2][font=\"times\"]_ L I N E _[/font]及[font=\"times\"]_ F I L E _[/font]宏指令在有关[font=\"times\"]# l i n e[/font]的部分中已讨论,这里讨论其余的宏名。[/size]
[size=2][font=\"times\"]_ D AT E _[/font]宏指令含有形式为月[font=\"times\"]/[/font]日[font=\"times\"]/[/font]年的串,表示源文件被翻译到代码时的日期。[/size]
[size=2]源代码翻译到目标代码的时间作为串包含在[font=\"times\"]_ T I M E _[/font]中。串形式为时:分:秒。[/size]
[size=2]如果实现是标准的,则宏[font=\"times\"]_ S T D C _[/font]含有十进制常量[font=\"times\"]1[/font]。如果它含有任何其它数,则实现是[/size]
[size=2]非标准的。[/size]
[size=2]可以定义宏,例如[font=\"times\"]:[/font][/size]
[size=2]当定义了[font=\"times\"]_DEBUG[/font],输出数据信息和所在文件所在行[/size]
[size=2][font=\"times\"]#ifdef _DEBUG[/font][/size]
[size=2][font=\"times\"]#define DEBUGMSG(msg,date) printf(msg);printf(“%d%d%d”,date,_LINE_,_FILE_)[/font][/size]
[size=2][font=\"times\"]#else[/font][/size]
[size=2][font=\"times\"]#define DEBUGMSG(msg,date)[/font][/size]
[size=2][font=\"times\"]#endif[/font][/size]
[size=2][font=\"times\"]20[/font],宏定义防止使用是错误[/size]
[size=2]用小括号包含。[/size]
[size=2]例如:[font=\"times\"]#define ADD(a,b) [/font]([font=\"times\"]a+b[/font])[/size]
[size=2]用[font=\"times\"]do{}while(0)[/font]语句包含多语句防止错误[/size]
[size=2]例如:[font=\"times\"]#difne DO(a,b) a+b;\[/font][/size]
[size=2][font=\"times\"]a++;[/font][/size]
[size=2]应用时:[font=\"times\"]if([/font]…[font=\"times\"].)[/font][/size]
[size=2][font=\"times\"]DO(a,b); //[/font]产生错误[/size]
[size=2][font=\"times\"]else[/font][/size]
[size=2]
[/size]
[size=2][b][color=#00f060]C语言中如何使用宏[/color][/b][/size]

[font=verdana,arial,helvetica,sans-serif]C(和C++)中的宏(Macro)属于编译器预处理的范畴,属于编译期概念(而非运行期概念)。下面对常遇到的宏的使用问题做了简单总结。
[b]宏使用中的常见的基础问题
[/b][b]#符号和##符号的使用
[/b][b]...符号的使用
[/b][b]宏的解释方法[/b]
[b]我们能碰到的宏的使用[/b]
[b]宏使用中的陷阱[/b]

[b]常见的基础性问题:[/b]

[b]关于#和##[/b]
在C语言的宏中,#的功能是将其后面的宏参数进行字符串化操作(Stringfication),简单说就是在对它所引用的宏变量通过替换后在其左右各加上一个双引号。比如下面代码中的宏:
#define WARN_IF(EXP) \
do{ if (EXP) \
fprintf(stderr, "Warning: " #EXP "\n"); } \
while(0)
那么实际使用中会出现下面所示的替换过程:
WARN_IF (divider == 0);
被替换为
do {
if (divider == 0)
fprintf(stderr, "Warning" "divider == 0" "\n");
} while(0);
这样每次divider(除数)为0的时候便会在标准错误流上输出一个提示信息。
而## 被称为连接符(concatenator),用来将两个Token连接为一个Token。注意这里连接的对象是Token就行,而不一定是宏的变量。比如你要做一个菜单项命令名和函数指针组成的结构体的数组,并且希望在函数名和菜单项命令名之间有直观的、名字上的关系。那么下面的代码就非常实用:
struct command
{
char * name;
void (*function) (void);
};
#define COMMAND(NAME) { NAME, NAME ## _command }
// 然后你就用一些预先定义好的命令来方便的初始化一个command结构的数组了:
struct command commands[] = {
COMMAND(quit),
COMMAND(help),
...
}
COMMAND宏在这里充当一个代码生成器的作用,这样可以在一定程度上减少代码密度,间接地也可以减少不留心所造成的错误。我们还可以n个##符号连接 n+1个Token,这个特性也是#符号所不具备的。比如:
#define LINK_MULTIPLE(a,b,c,d) a##_##b##_##c##_##d
typedef struct _record_type LINK_MULTIPLE(name,company,position,salary);
// 这里这个语句将展开为:
// typedef struct _record_type name_company_position_salary;

[b]关于...的使用
[/b]...在C宏中称为Variadic Macro,也就是变参宏。比如:
#define myprintf(templt,...) fprintf(stderr,templt,__VA_ARGS__)
// 或者
#define myprintf(templt,args...) fprintf(stderr,templt,args)
第一个宏中由于没有对变参起名,我们用默认的宏__VA_ARGS__来替代它。第二个宏中,我们显式地命名变参为args,那么我们在宏定义中就可以用 args来代指变参了。同C语言的stdcall一样,变参必须作为参数表的最有一项出现。当上面的宏中我们只能提供第一个参数templt时,C标准要求我们必须写成:
myprintf(templt,);
的形式。这时的替换过程为:
myprintf("Error!\n",);
替换为:
fprintf(stderr,"Error!\n",);
这是一个语法错误,不能正常编译。这个问题一般有两个解决方法。首先,GNU CPP提供的解决方法允许上面的宏调用写成:
myprintf(templt);
而它将会被通过替换变成:
fprintf(stderr,"Error!\n",);
很明显,这里仍然会产生编译错误(非本例的某些情况下不会产生编译错误)。除了这种方式外,c99和GNU CPP都支持下面的宏定义方式:
#define myprintf(templt, ...) fprintf(stderr,templt, ##__VAR_ARGS__)
这时,##这个连接符号充当的作用就是当__VAR_ARGS__为空的时候,消除前面的那个逗号。那么此时的翻译过程如下:
myprintf(templt);
被转化为:
fprintf(stderr,templt);
这样如果templt合法,将不会产生编译错误。
[b]宏是如何解释的[/b]
[b]宏在日常编程中的常见使用[/b]
[b]宏使用中的陷阱[/b]
这里列出了一些宏使用中容易出错的地方,以及合适的使用方式。
[b]错误的嵌套-Misnesting[/b]
宏的定义不一定要有完整的、配对的括号,但是为了避免出错并且提高可读性,最好避免这样使用。
由操作符优先级引起的问题-Operator Precedence Problem
由于宏只是简单的替换,宏的参数如果是复合结构,那么通过替换之后可能由于各个参数之间的操作符优先级高于单个参数内部各部分之间相互作用的操作符优先级,如果我们不用括号保护各个宏参数,可能会产生预想不到的情形。比如:
#define ceil_div(x, y) (x + y - 1) / y
那么
a = ceil_div( b & c, sizeof(int) );
将被转化为:
a = ( b & c + sizeof(int) - 1) / sizeof(int);
// 由于+/-的优先级高于&的优先级,那么上面式子等同于:
a = ( b & (c + sizeof(int) - 1)) / sizeof(int);
这显然不是调用者的初衷。为了避免这种情况发生,应当多写几个括号:
define ceil_div(x, y) (((x) + (y) - 1) / (y))
消除多余的分号-Semicolon Swallowing
通常情况下,为了使函数模样的宏在表面上看起来像一个通常的C语言调用一样,通常情况下我们在宏的后面加上一个分号,比如下面的带参宏:
MY_MACRO(x);
但是如果是下面的情况:
#define MY_MACRO(x) { \
/* line 1 */ \
/* line 2 */ \
/* line 3 */ }
//...
if (condition())
MY_MACRO(a);
else
{...}
这样会由于多出的那个分号产生编译错误。为了避免这种情况出现同时保持MY_MACRO(x);的这种写法,我们需要把宏定义为这种形式:
#define MY_MACRO(x) do {
/* line 1 */ \
/* line 2 */ \
/* line 3 */ } while(0)
这样只要保证总是使用分号,就不会有任何问题。
[b]Duplication of Side Effects[/b]
这里的Side Effect是指宏在展开的时候对其参数可能进行多次Evaluation(也就是取值),但是如果这个宏参数是一个函数,那么就有可能被调用多次从而达到不一致的结果,甚至会发生更严重的错误。比如:
#define min(X,Y) ((X) > (Y) ? (Y) : (X))
//...
c = min(a,foo(b));
这时foo()函数就被调用了两次。为了解决这个潜在的问题,我们应当这样写min(X,Y)这个宏:
#define min(X,Y) ({ \
typeof (X) x_ = (X); \
typeof (Y) y_ = (Y); \
(x_ < y_) ? x_ : y_; })
({...})的作用是将内部的几条语句中最后一条的值返回,它也允许在内部声明变量(因为它通过大括号组成了一个局部Scope)。[/font]
页: [1]
查看完整版本: C语言宏定义使用技巧