大型程序或者修改别人的程序时,当我们需要定义常量(源文件还是头文件 ),我们就必须返回检查原来此常量是否已经定义,
if defined宏 就是用于检测的。
举个例子,如下:
#define ....
#define .... .... ....
#define Dataauto 1 ....
要检查Dataauto是否定义,或者我们要给Dataauto一个不同的值,可以添加语句
#if defined a
#undef Dataauto
#define Dataauto 0
#endif 上述语句检验Dataauto是否被定义,如果被定义,则用#undef语句解除定义,并重新定义Dataauto为0
同样,检验Dataauto是否定义:
#ifndef Dataauto //如果Dataauto没有被定义
#define Dataauto 0
#endif
以上所用的宏中:#undef为解除定义,#ifndef是if not defined的缩写,即如果没有定义。
这就是#if defined 的唯一作用!
1) #if defined XXX_XXX
#endif 是条件编译,是根据你是否定义了XXX_XXX这个宏,而使用不同的代码。
一般.h文件里最外层的
#if !defined XXX_XXX
#define XXX_XXX
#endif 是为了避免.h头文件被重复include。
2) #error XXXX 是用来产生编译时错误信息XXXX的,一般用在预处理过程中;
例子:
#if !defined(__Dataauto)
#error C++ compiler required.
#endif
引用别人的英文用法说明:
The special operator defined is used in #if and #elif expressions to test whether a certain name is defined as a macro.
defined name and defined (name) are both expressions whose value is 1 if name is defined as a macro at the current point in the program, and 0 otherwise.
Thus, #if defined MACRO is precisely equivalent to #ifdef MACRO. defined is useful when you wish to test more than one macro for existence at once.
For example, #if defined (__vax__) || defined (__ns16000__) would succeed if either of the names __vax__ or __ns16000__ is defined as a macro. Conditionals written like this: #if defined BUFSIZE && BUFSIZE >= 1024 can generally be simplified to just #if BUFSIZE >= 1024, since if BUFSIZE is not defined, it will be interpreted as having the value zero.
If the defined operator appears as a result of a macro expansion, the C standard says the behavior is undefined. GNU cpp treats it as a genuine defined operator and evaluates it normally. It will warn wherever your code uses this feature if you use the command-line option -pedantic, since other compilers may handle it differently .