分类:
2013-04-08 10:40:38
原文地址:#define 用法总结 作者:js_jammy
#define DECLARE_RTTI(thisClass, superClass)\
virtual const char* GetClassName() const\
{return #thisClass;}\
static int isTypeOf(const char* type)\
{\
if(!strcmp(#thisClass, type)\
return 1;\
return superClass::isTypeOf(type);\
return 0;\
}\
virtual int isA(const char* type)\
{\
return thisClass::isTypeOf(type);\
}\
static thisClass* SafeDownCast(DitkObject* o)\
{\
if(o&&o->isA(#thisClass))\
return static_cast(o);\
return NULL;\
}
5. 用于条件编译:(常用形式)
#ifndef _AAA_H
#define _AAA_H
//c/c++代码
#endif
在大规模的开发过程中,特别是跨平台和系统的软件里,define最重要的功能是条件编译。就是:
#ifdef WINDOWS
......
......
#endif
#ifdef LINUX
......
......
#endif
可以在编译的时候通过#define设置编译环境
5.如何定义宏、取消宏
//定义宏
#define [MacroName] [MacroValue]
//取消宏
#undef [MacroName]
普通宏
#define PI (3.1415926)
带参数的宏
#define max(a,b) ((a)>(b)? (a),(b))
关键是十分容易产生错误,包括机器和人理解上的差异等等。
6.条件编译
#ifdef XXX…(#else) …#endif 例如 #ifdef DV22_AUX_INPUT #define AUX_MODE 3 #else #define AUY_MODE 3 #endif #ifndef XXX … (#else) … #endif
7.头文件(.h)可以被头文件或C文件包含;
重复包含(重复定义)
由于头文件包含可以嵌套,那么C文件就有可能包含多次同一个头文件,就可能出现重复定义的问题的。
通过条件编译开关来避免重复包含(重复定义)
例如
#ifndef __headerfileXXX__
#define __headerfileXXX__
…
文件内容
…
#endif
8. 一些注意事项:
1) 不能重复定义.除非定义完全相同.#define A(x) … 和#define A 是重复定义.
2) 可以只定义符号,不定义值.如#define AAA