1. 简单的 define 定义
#define PI (3.1415926)
2. 带参数的宏定义
#define MAX(a,b) ((a) > (b) ? (a) : (b))
3. define 字符串连接以及变量名分段联结用法
#define A(x) ##x#define B(x) #@x
#define C(x) #x
如果我们假设x=a,那么A(a)就是a,B(a)就是‘a’,C(1)就是”a“
// 字符串转化用法
#define TO_STRING( s ) #s
编译前:
cout < < TO_STRING( Hello World! ) < < endl;
编译后:
cout < < "Hello World!" < < endl;
// 变量名的预编译联结用法
#define TO_VALUE( a, b ) a##b
编译前:
cout < < TO_VALUE( plea, se ) < < endl;
编译后:
cout < < please < < endl;
4. define 的多行定义
#define MACRO( arg1, arg2 ) do { \test1; \
test2; \
}while(0)
5. 定义宏和取消宏定义的方法
定义宏:#define取消宏:#undef
6. 使用宏进行条件编译
#ifdef … (#else) … #endif#if 1 … (#else) … #endif
7. 防止重复编译格式
#ifndef _HELLO_H_#define _HELLO_H_
...
//文件内容
...
#endif
8.MFC消息映射的两个宏定义
// MFC消息路由宏
#define BEGIN_MESSAGE_MAP(theClass, baseClass) \
PTM_WARNING_DISABLE \
const AFX_MSGMAP* theClass::GetMessageMap() const \
{ return GetThisMessageMap(); } \
const AFX_MSGMAP* PASCAL theClass::GetThisMessageMap() \
{ \
typedef theClass ThisClass; \
typedef baseClass TheBaseClass; \
static const AFX_MSGMAP_ENTRY _messageEntries[] = \
{
#define END_MESSAGE_MAP() \
{0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 } \
}; \
static const AFX_MSGMAP messageMap = \
{ &TheBaseClass::GetThisMessageMap, &_messageEntries[0] }; \
return &messageMap; \
}