概念
宏(macro)是在预处理阶段进行文本替换的一种机制, 通过 #define 定义
特点是编译时展开, 不占运行时内存; 可以用于定义常量、函数或条件编译
普通宏
#include <stdio.h>
#define MAX(x, y) x > y ? x : y
int main() {
int x = 3;
int y = 4;
int z = MAX(x, y);
// 4
printf("%d\n", z);
return 0;
}
内置宏
预处理
| 指令 |
说明 |
# |
空指令, 无任何效果 |
#include |
包含一个源代码文件 |
#define |
定义宏 |
#undef |
取消已定义宏 |
#if |
若给定条件为真,则编译下面代码 |
#ifdef
#if defined |
若宏已经定义,则编译下面代码 |
#ifndef |
若宏没有定义,则编译下面代码 |
#elif |
若前面#if给定条件不为真, 且当前条件为真 |
#endif |
结束一个#if…#else条件编译块 |
#ifndef __INCLUDE_HPP__
#define __INCLUDE_HPP__
// ...
#endif
#define FLAG
// 等价于 #ifdef FLAG
#if defined(FLAG)
// ...
#endif
#undef FLAG
系统
| 宏名 |
说明 |
_WIN32 |
在所有wndows(32/64位)上都定义 |
_WIN64 |
仅在64位windows上定义 |
__linux__ |
在linux上定义 |
__unix__ |
在unix上定义 |
__APPLE__ |
在apple上定义 |
__ANDROID__ |
在安卓上定义 |
#include <iostream>
int main() {
#if defined(_WIN64)
std::cout << "Windows 64" << std::endl;
#elif defined(__linux__)
std::cout << "Linux" << std::endl;
#elif defined(__unix__)
std::cout << "Unix" << std::endl;
#elif defined(__APPLE__)
std::cout << "Apple" << std::endl;
#elif defined(__ANDROID__)
std::cout << "Android" << std::endl;
#endif
return 0;
}
c++版本
__cplusplus 是c++编译器特有宏, 只在c++编译器中定义, 显示当前支持c++版本
| 值 |
说明 |
199711L |
c++98/03 |
201103L |
c++11 |
201402L |
c++14 |
201703L |
c++17 |
202002L |
c++20 |
#include <iostream>
int main() {
#if __cplusplus >= 202002L
std::cout << "c++20 or newer\n";
#elif __cplusplus >= 201703L
std::cout << "c++17\n";
#elif __cplusplus >= 201402L
std::cout << "c++14\n";
#elif __cplusplus >= 201103L
std::cout << "c++11\n";
#else
std::cout << "c++98/03 or older\n";
#endif
return 0;
}
功能宏
| 宏 |
说明 |
__LINE__ |
表示当前行号, 整型 |
__FILE__ |
表示当前文件名, 字符串类型 |
__DATE__ |
编译日期, 字符串类型 |
__TIME__ |
编译时间, 字符串类型 |
__FUNCTION__ |
当前函数名 |
#include <iostream>
void hello() {
std::cout << "file: " << __FILE__ << std::endl;
std::cout << "line: " << __LINE__ << std::endl;
std::cout << "date: " << __DATE__ << std::endl;
std::cout << "time: " << __TIME__ << std::endl;
std::cout << "func: " << __FUNCTION__ << std::endl;
}
int main() {
hello();
return 0;
}