我看到这种情况一直在发生,例如在 Linux 内核中。使用预处理器命令与普通 C++ if else 块相比的目的是什么?有速度优势什么的吗?
预处理器会在编译之前更改 C/C++ 代码(因此称为 pre 处理器)。
预处理器 ifs 在编译时进行评估。
C/C++ ifs 在运行时进行评估。
针对不同平台或不同编译器调整代码:
#ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */
#include <unistd.h>
#elif defined _WIN32 /* _Win32 is usually defined by compilers targeting 32 or 64 bit Windows systems */
#include <windows.h>
#endif
确保头文件定义仅包含一次(相当于
#pragma once
,但更便携):
#ifndef EXAMPLE_H
#define EXAMPLE_H
class Example { ... };
#endif
void some_debug_function() {
#ifdef DEBUG
printf("Debug!\n");
#endif
}
现在,当未定义
DEBUG
进行编译时(可能是编译器的命令行参数),编译器可以优化对
some_debug_function
的任何调用。
#if DEBUG
int a;
#else
double b;
#endif
gcc -c -DDEBUG=1 file.c 将看到“int a”
gcc -c file.c 将看到“double b”
#include <iostream>
using namespace std;
int main() {
#if 1
cerr<<"Preprocessor directives used";
#endif
if(0){
int a=10;
}
return 0;
}
#if 0
int 10 = a;
int a = "hello";
#endif