2007年11月19日 星期一 08:48 A.M.

我们可能要定义很多常量( 不管是放在源文件还是头文件 ),那么我们有时考虑定义某个常量时,我们就必须返回检查原来此常量是否定义,但这样做很麻烦.if defined宏正是为这种情况提供了解决方案.举个例子,如下:

#define ....
#define ....
........
........
#define a 100
.......
此时,我们要检查a是否定义(假设我们已经记不着这点了),或者我们要给a一个不同的值,就加入如下句子
#if defined a
#undef a
#define a 200
#endif
上述语句检验a是否被定义,如果被定义,则用#undef语句解除定义,并重新定义a为200

同样,检验a是否定义:
#ifndef a //如果a没有被定义
#define a 100
#endif

以上所用的宏中:#undef为解除定义,#ifndef是if not defined的缩写,即如果没有定义。

这就是#if defined 的唯一作用

 

常用宏定义总结



*pclint///////////////////////////////////*lint -save -e* */ /*此处屏蔽所有告警*/#include <stdio.h>/*lint -restore */ /*此处打开lint 告警检查*/
/////////////////////////////////*通过开关定义打印,1开0关,且调用处不需要宏控制////////////////////////////////*DEBUG DEFINE BEGIN*/#define VPLS_EXT_DEBUG 1 /*开关*/
#if VPLS_EXT_DEBUG#define _VE_DEBUG(msg...) printf("[VPLS_DEBUG] %s,%d => ",__FILE__, __LINE__);printf(msg);printf("\r\n")#else#define _VE_DEBUG(x1,x2) (void)(x1),(void)(x2)#endif/*DEBUG DEFINE END*/
调用直接写为_VE_DEBUG("XXXXX %d",adb)开关关闭后这句直接失效//////////////////////////////
main(void){            int a,b,c,d;       a = b =   c =   d = 9;
       _BUG("a = %d,b = %d,c = %d,d = %d\n",a,b,c,d);
}     
/*断言,只提示不处理*/#define assert(e)\         ((void)((e) || fprintf(stderr,"line %d: 'assert error!'\n",__LINE__)))////////////////////////////////////__attribute__ 作用- -                                        __attribute__ 是GCC的关键字,描述变量的属性。
下面举几例内核中常见的:
__attribute__((regparm(0))) int printk(const char * fmt, ...) __attribute__ ((format (printf, 1, 2)));禁止printk使用寄存器传递调用参数,并将printk的参数1作为printf格式串,从参数2开始检查其类型;
void __switch_to(struct task_struct *prev, struct task_struct *next) __attribute__((regparm(3))) ;__switch_to保留3个寄存器用作传递参数;
void __attribute__ ((__section__ (".text.init"))) mem_init();将mem_init编绎到.text.init段;
struct tasklet_head tasklet_vec[32 ] __attribute__((__aligned__((32)),__section__(".data.cacheline_aligned"))) ;将tasklet_vec[32]编绎到.data.cacheline_aligned段,并将它在32字节边界上对齐;
void do_exit(long error_code)__attribute__((noreturn));do_exit不会返回;
struct Xgt_desc_struct { unsigned short size; unsigned long address __attribute__((packed));};将address在结构中紧凑排列




今天,和一位网友Oasis谈了一些关于宏定义的一些问题,颇有所得。特录于此。起因是他看到open sourc中经常有这样的源码,感觉无法理解:#define swap(a,b) do {int tmp;tmp = (a);(a) = (b);(b) = tmp;}while(0)。总感觉这样的定义中的do-while有点蛇足的味道,感觉真的是没有什么必要。开始我也是这样觉得的,因为是while(0)嘛,总感觉不用do-while,只用{}也是可以解决问题的。后来我们经过测试得出这样的结论:用这个语句,完全是程序员追求严谨的性格决定的风格。因为如果这样定义宏,那么如上面的swap宏,就只能像函数一样使用,这样在句子后面跟上分号:swap(a,b);。而如果只用{}来定义的话,那么使用中加不加分号就都可以了,就会比较混乱而且不严谨。
如果使用{}的话,会在if else语句中加分号不好用。而且,强制加分号,表明了这个宏不可以当作操作数来使用。
C语言宏定义技巧- -                                        C语言宏定义技巧(常用宏定义)   写好C语言,漂亮的宏定义很重要,使用宏定义可以防止出错,提高可移植性,可读性,方便性 等等。下面列举一些成熟软件中常用得宏定义。。。。。。

1,防止一个头文件被重复包含
#ifndef COMDEF_H
#define COMDEF_H
   //头文件内容
#endif
2,重新定义一些类型,防止由于各种平台和编译器的不同,而产生的类型字节数差异,方便移植。
typedef   unsigned char       boolean;      /* Boolean value type. */

typedef   unsigned long int   uint32;       /* Unsigned 32 bit value */

typedef   unsigned short      uint16;       /* Unsigned 16 bit value */
typedef   unsigned char       uint8;        /* Unsigned 8   bit value */

typedef   signed long int     int32;        /* Signed 32 bit value */
typedef   signed short        int16;        /* Signed 16 bit value */
typedef   signed char         int8;         /* Signed 8   bit value */


//下面的不建议使用
typedef   unsigned char      byte;          /* Unsigned 8   bit value type. */
typedef   unsigned short     word;          /* Unsinged 16 bit value type. */
typedef   unsigned long      dword;         /* Unsigned 32 bit value type. */

typedef   unsigned char      uint1;         /* Unsigned 8   bit value type. */
typedef   unsigned short     uint2;         /* Unsigned 16 bit value type. */
typedef   unsigned long      uint4;         /* Unsigned 32 bit value type. */

typedef   signed char        int1;          /* Signed 8   bit value type. */
typedef   signed short       int2;          /* Signed 16 bit value type. */
typedef   long int           int4;          /* Signed 32 bit value type. */

typedef   signed long        sint31;        /* Signed 32 bit value */
typedef   signed short       sint15;        /* Signed 16 bit value */
typedef   signed char        sint7;         /* Signed 8   bit value */

3,得到指定地址上的一个字节或字
#define   MEM_B( x )   ( *( (byte *) (x) ) )
#define   MEM_W( x )   ( *( (word *) (x) ) )
4,求最大值和最小值
    #define   MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )
    #define   MIN( x, y ) ( ((x) < (y)) ? (x) : (y) )
5,得到一个field在结构体(struct)中的偏移量
#define FPOS( type, field ) \
/*lint -e545 */ ( (dword) &(( type *) 0)-> field ) /*lint +e545 */
6,得到一个结构体中field所占用的字节数
#define FSIZ( type, field ) sizeof( ((type *) 0)->field )
7,按照LSB格式把两个字节转化为一个Word
#define   FLIPW( ray ) ( (((word) (ray)[0]) * 256) + (ray)[1] )
8,按照LSB格式把一个Word转化为两个字节
#define   FLOPW( ray, val ) \
   (ray)[0] = ((val) / 256); \
   (ray)[1] = ((val) & 0xFF)
9,得到一个变量的地址(word宽度)
#define   B_PTR( var )   ( (byte *) (void *) &(var) )
#define   W_PTR( var )   ( (word *) (void *) &(var) )
10,得到一个字的高位和低位字节
#define   WORD_LO(xxx)   ((byte) ((word)(xxx) & 255))
#define   WORD_HI(xxx)   ((byte) ((word)(xxx) >> 8))
11,返回一个比X大的最接近的8的倍数
#define RND8( x )        ((((x) + 7) / 8 ) * 8 )
12,将一个字母转换为大写
#define   UPCASE( c ) ( (© >= 'a' && © <= 'z') ? (© - 0x20) : © )
13,判断字符是不是10进值的数字
#define   DECCHK( c ) (© >= '0' && © <= '9')
14,判断字符是不是16进值的数字
#define   HEXCHK( c ) ( (© >= '0' && © <= '9') ||\
                        (© >= 'A' && © <= 'F') ||\
(© >= 'a' && © <= 'f') )
15,防止溢出的一个方法
#define   INC_SAT( val )   (val = ((val)+1 > (val)) ? (val)+1 : (val))
16,返回数组元素的个数只对直接数组名有效,数组指针无效
#define   ARR_SIZE( a )   ( sizeof( (a) ) / sizeof( (a[0]) ) )
17,返回一个无符号数n尾的值MOD_BY_POWER_OF_TWO(X,n)=X%(2^n)
#define MOD_BY_POWER_OF_TWO( val, mod_by ) \
            ( (dword)(val) & (dword)((mod_by)-1) )
18,对于IO空间映射在存储空间的结构,输入输出处理
   #define inp(port)          (*((volatile byte *) (port)))
   #define inpw(port)         (*((volatile word *) (port)))
   #define inpdw(port)        (*((volatile dword *)(port)))
  
   #define outp(port, val)    (*((volatile byte *) (port)) = ((byte) (val)))
   #define outpw(port, val)   (*((volatile word *) (port)) = ((word) (val)))
   #define outpdw(port, val) (*((volatile dword *) (port)) = ((dword) (val)))
19,使用一些宏跟踪调试
A N S I标准说明了五个预定义的宏名。它们是:
_ L I N E _
_ F I L E _
_ D A T E _
_ T I M E _
_ S T D C _
如果编译不是标准的,则可能仅支持以上宏名中的几个,或根本不支持。记住编译程序
也许还提供其它预定义的宏名。
_ L I N E _及_ F I L E _宏指令在有关# l i n e的部分中已讨论,这里讨论其余的宏名。
_ D AT E _宏指令含有形式为月/日/年的串,表示源文件被翻译到代码时的日期。
源代码翻译到目标代码的时间作为串包含在_ T I M E _中。串形式为时:分:秒。
如果实现是标准的,则宏_ S T D C _含有十进制常量1。如果它含有任何其它数,则实现是
非标准的。
可以定义宏,例如:
当定义了_DEBUG,输出数据信息和所在文件所在行
#ifdef _DEBUG
#define DEBUGMSG(msg,date) printf(msg);printf(“%d%d%d”,date,_LINE_,_FILE_)
#else
       #define DEBUGMSG(msg,date)
#endif

20,宏定义防止使用是错误
用小括号包含。
例如:#define ADD(a,b) (a+b)
用do{}while(0)语句包含多语句防止错误
例如:#difne DO(a,b) a+b;\
                    a++;
应用时:if(….)
           DO(a,b); //产生错误
         else
        
解决方法: #difne DO(a,b) do{a+b;\
                    a++;}while(0)
用这个宏来跟踪错误