ifndef详细信息#ifndef是“if not defined”的缩写,是预处理功能宏定义、文件包含、条件编译)中的条件编译,可以根据变量是否已经定义进行分支选择
易于调试和移植防止重复包含和编译头文件的程序
以下分别举例说明。
一、防止头文件重复包含和编译
错误的演示如下所示。
headfile_1.h
1 # include iostream2class CT est _1{ 3c test _1) { 4 //do something,eg:init; 6) CTest_1) ) { 7 //do something,eg:free; 8 } 9 void PrintScreen ) 10 ) 11 STD 33603360 cout ‘ thisisclassctest _ 1!’ std:endl; 12 ) 13}; headfile_2.h
1 # include ‘ headfile _1. h ‘2class CT est _2{ 3c test _2} {4//do something,eg:init; 6) CTest_2) ) { 7 //do something,eg:free; 8 }9void打印屏幕) 10 ) 11 STD 33603360 cout ‘ thisisclassctest _ 2!’ std:endl; 12 ) 13}; sourcefile.cpp
1 # include iostream2# include ‘ headfile _1. h ‘3# include ‘ headfile _2. h ‘ 45 int main 6)6 {7 return 0; 8 }编译时提示重新定义错误:
上面显示了headfile_1.h类CTest_1的重新定义。
通常,有一个c源文件,如sourcefile.cpp,其中包含两个头文件,如headfile_1.h和headfile_2.h,头文件headfile_2.h中包含headfile
添加条件编译“ifndef”可以解决问题。 将条件编译添加到headfile_1.h中时,会出现以下情况:
headfile_1.h
1 # ifndef _ headfile _1_ H2 # define _ headfile _1_ H3 # include iostream4class CT est _1{ 5c test _1)///10 ) 11 void打印屏幕12 ) 13 STD 33603360 cout ‘ thisisclassctest _ 1!’ std:endl; 14 }15 }; 16 17 #endif //end of _HEADFILE_1_H编译通过!
分析:第一次包含headfile_1.h时,_HEADFILE_1_H未定义,因此条件为true,执行#ifndef _HEADFILE_1_H和#endif之间的代码如果第二次包含headfile_1.h,则如果之前已经定义了_HEADFILE_1_H且条件为假,则还会再次包含#ifndef _HEADFILE_1_H和#endif之间的代码
总结:将头文件的内容放入#ifndef和#endif中。 无论头文件是否被多个文件引用,都最好添加它。 一般格式如下。
#ifndef标记#define标记. #endif标记在理论上可以自由命名,但对于每个头文件,此标记必须是唯一的。 的标记通常开头的文件名都是大写的,开头加下划线,文件名中的’.’也是下划线。 例如stdio.h
#ifndef _ stdio _ h # define _ stdio _ h . # endif注意: # ifndef不会防止两个源文件多次包含相同的头文件,而是在一个源文件中包含相同的头文件事实上,防止同一头文件包含在两个不同的源文件中的要求本身是不合理的,头文件的存在价值是包含在不同的源文件中。
二、程序调试和移植方便
调试程序时,经常需要选择性地编译程序的内容,您可以选择是否根据一定的条件进行编译。
主要分为以下几类。
1、
#ifndef标识符段1#else段2#endif如果“标识符”未在#define中定义,则编译“段1”;否则编译“段2”
2,
#ifndef标识符#define标识符段1#else段2#endif如果“标识符”未由#define定义,则编译“段1”;否则编译“段2”
3、
#if表达式段1#else段2#endif如果“表达式”的值为真,则编译“段1”,否则编译“段2”。
注:在上述三种形式中,#else不是强制的,可以省略; 当然,如果需要在#else之后嵌套#if,则可以使用预处理命令#elif。 这相当于#else#if。
总结:在程序中使用条件编译主要是为了方便程序的调试和移植。
转载来源: https://www.cn blogs.com/coding mengmeng/p/7221295.html