写好C语言,漂亮的宏定义很重要

2019-07-18 14:30发布

写好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)


0条回答

一周热门 更多>