C 语言宏定义技巧(常用宏定义)
等等。写好 C 语言,漂亮的宏定义很重要,使用宏定义可以防止出错,提高可移植性,可读性,方便性 下面列举一些成熟软件中常用得宏定义、 、、、、、
等等。
防止一个头文件被重复包含
#ifndef COMDEF_H
#define COMDEF_H
//头文件内容
#endif
重新定义一些类型,防止由于各种平台和编译器的不同,而产生的类型字节数差异,方便 移植。
typedef
unsigned char
boolean;
typedef
unsigned long int
uint32;
typedef
unsigned short
uint16;
typedef
unsigned char
uint8;
typedef
signed long int
int32;
typedef
signed short
int16;
typedef
signed char
int8;
//下面的不建议使用
typedef
unsigned char
byte;
typedef
unsigned short
word;
typedef
unsigned long
dword;
typedef
unsigned char
uint1;
typedef
unsigned short
uint2;
typedef
unsigned long
uint4;
typedef
signed char
int1;
typedef
signed short
int2;
typedef
long int
int4;
typedef
signed long
sint31;
typedef
signed short
sint15;
typedef
signed char
sint7;
/* Boolean value type. */ /* Unsigned 32 bit value */
/* Unsigned 16 bit value */
/* Unsigned 8 bit value */
/* Signed 32 bit value */
/* Signed 16 bit value */
/* Signed 8 bit value */
/* Unsigned 8 bit value type. */ /* Unsinged 16 bit value type. */ /* Unsigned 32 bit value type. */
/* Unsigned 8 bit value type. */ /* Unsigned 16 bit value type. */ /* Unsigned 32 bit value type. */ /* Signed 8 bit value type. */ /* Signed 16 bit value type. */ /* Signed 32 bit value type. */ /* Signed 32 bit value */ /* Signed 16 bit value */
/* Signed 8 bit value */
得到指定地址上的一个字节或字
#define MEM_B( x ) ( *( (byte *) (x) ) )
#define MEM_W( x ) ( *( (word *) (x) ) )
求最大值和最小值
#define MAX( x, y ) ( ((x) > (y)) ? (x) : (y) )
#define MIN( x, y ) ( ((x) < (y)) ? (x) : (y) )
得到一个field在结构体(struct中的偏移量
#define FPOS( type, field ) \
/*lint -e545 */ ( (dword) &(( type *) 0)-> field ) /*lint +e545 */
得到一个结构体中field所占用的字节数
#define FSIZ( type, field ) sizeof( ((type *) 0)->field )
按照 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)
得到一个变量的地址(word宽度)
#define B_PTR( var ) ( (byte *) (void *) &(var) )
#define W_PTR(