空枝|C|深入理解库中随处可见的宏( 三 )


对于一些简单的函数 , 程序员通常使用宏:
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))#define ABS(X) ((X) < 0 ? -(X) : (X))#define ISSIGN(X) ((X) == '+' || (X) == '-' ? 1 : 0)6 取消宏定义#undef指令可以取消宏定义 , 如:
#define LIMIT 444#undef LIMIT7 头文件的保护性定义#ifndef指令判断后面的标识符是否未定义 , 可以防止相同的宏被重复定义 。 但更常用来防止多次(重复)包含一个文件 , 也就是保护性定义:
#ifndef _HEADERNAME_H_#define _HEADERNAME_H_... // 头文件内容#endif8 预定义宏C编译器有一些预定义宏和标识符:
// predef.c -- predefined identifiers#include void why_me();int main(){printf("The file is %s.\n", __FILE__);printf("The date is %s.\n", __DATE__);printf("The time is %s.\n", __TIME__);printf("The version is %ld.\n", __STDC_VERSION__);printf("This is line %d.\n", __LINE__);printf("This function is %s\n", __func__);why_me();getchar();return 0;}void why_me(){printf("This function is %s\n", __func__);printf("This is line %d.\n", __LINE__);}/*This is line 11.This function is mainThis function is why_meThis is line 21. */9 宏的经典应用在MFC的消息映射 , 就是宏的一个经典应用:
#define DECLARE_MESSAGE_MAP() \private: \ static const AFX_MSGMAP_ENTRY _messageEntries[]; \protected: \ static AFX_DATA const AFX_MSGMAP messageMap; \ static const AFX_MSGMAP* PASCAL _GetBaseMessageMap(); \ virtual const AFX_MSGMAP* GetMessageMap() const; \#define BEGIN_MESSAGE_MAP(theClass, baseClass) /const AFX_MSGMAP* theClass::GetMessageMap() const /{ return} /AFX_COMDAT AFX_DATADEF const AFX_MSGMAP theClass::messageMap = /{/AFX_COMDAT const AFX_MSGMAP_ENTRY theClass::_messageEntries[] = /{ /#define END_MESSAGE_MAP() /{0, 0, 0, 0, AfxSig_end, (AFX_PMSG)0 } /}; /宏的定义一般放到头文件中 , 如一些库中就通常包含有宏定义 。
宏替换表面看起来有很多缺陷 , 但在一些库中却用得很普通 , 如果不是很熟悉的话 , 一些源代码还真是看得云里雾里的 。
【空枝|C|深入理解库中随处可见的宏】
-End-


推荐阅读