条件编译主要在两个地方常见:
头文件(.h)&& 源文件(.cpp)

先来介绍他们的作用

在头文件中进行条件编译一般是在文件的开头,这个主要是为了防止头文件重复覆盖增加存储

#ifndef __STACK_H__   // 如果没有定义这个表达式
#define __STACK_H__ // 就定义这个表达式
#include <iostream>
class stu {};
#endif // 结束

源文件中的定义比较广泛了,但是也主要是为了条件语句,为了让代码可以更好的在计算机上运行

  • #define 定义一个预处理宏
  • #undef 取消宏的定义
  • #if 编译预处理中的条件命令,相当于C语法中的if语句
  • #ifdef 判断某个宏是否被定义,若已定义,执行随后的语句
  • #ifndef 与#ifdef相反,判断某个宏是否未被定义
  • #elif 若#if, #ifdef, #ifndef或前面的#elif条件不满足,则执行#elif之后的语句,相当于C语法中的else-if
  • #else 与#if, #ifdef, #ifndef对应, 若这些条件不满足,- 则执行#else之后的语句,相当于C语法中的else
  • #endif #if, #ifdef, #ifndef这些条件命令的结束标志.
  • defined  与#if, #elif配合使用,判断某个宏是否被定义
#include <iostream>
#define N 1 // 定义一个宏
int main() {
#ifdef N // 如果已经定义了这个宏执行
std::cout << "hello world" << std::endl;
#else // 否则执行下面的语句
std::cout << "happy new year" << std::endl;
#endif // 条件编译结束
return 0; // 主进程结束
}
output$: hello world

接下来来看看相反的ifndef

#include <iostream>
#define N 1 // 定义一个宏
int main() {
#ifndef N // 如果没有定义了这个宏执行
std::cout << "hello world" << std::endl;
#else // 否则执行下面的语句
std::cout << "happy new year" << std::endl;
#endif // 条件编译结束
return 0; // 主进程结束
}
output$: happy new year

好了,最后来看看正常的条件语句:
#if可支持同时判断多个宏的存在

#include <iostream>
#define N 1
int main() {
#if N // 宏N如果存在
std::cout << "hello world" << std::endl;
#elif M // 宏M如果存在
std::cout << "happy new year" << std::endl;
#elif V // 宏V如果存在
std::cout << "nooooooooo" << std::endl;
#else // 其他
std::cout << "byebye" << std::endl;
#endif
return 0;
}