目录
一、宏替换 #define
1. 定义常量
#define PI 3.1415926
2. 定义函数
#define MAX(a, b) ((a) > (b) ? (a) : (b))
3. 定义代码块
#define DO_SOMETHING { \
printf("Hello, "); \
printf("world!"); \
}
二、条件编译 #if
指令 | 作用 |
---|---|
#ifdef | 如果定义了某个宏,则编译下面的代码。 |
#ifndef | 如果没有定义某个宏,则编译下面的代码。 |
#if | 根据条件编译下面的代码。 |
#else | 当上一个条件不成立时,编译下面的代码。 |
#elif | 当上一个条件不成立时,根据新条件编译下面的代码。 |
#endif | 结束一个条件编译模块。 |
1. 使用 #ifdef
、 #else
和 #endif
编译不同平台的代码
#ifdef _WIN32
// Windows 平台下的代码
#include <windows.h>
#else
// 非 Windows 平台下的代码
#include <unistd.h>
#endif
2. 使用 #if
、#elif
、#else
和 #endif
编译不同版本的代码
#define VERSION 3
#if VERSION == 1
// 版本 1 的代码
#elif VERSION == 2
// 版本 2 的代码
#elif VERSION == 3
// 版本 3 的代码
#else
// 其他版本的代码
#endif
3. 使用 #ifndef
和 #define
和#endif
防止头文件重复包含
#ifndef _MY_HEADER_H_
#define _MY_HEADER_H_
/* 这里是头文件的内容 */
#endif /* _MY_HEADER_H_ */
三、头文件包含 #include
1. 头文件两种写法
用尖括号<>
括起来
表示该头文件是标准库文件或系统文件,编译器会在标准库和系统包含路径中查找该头文件。
#include <iostream>
用双引号""
括起来
表示该头文件是用户自定义的文件,编译器会在当前编译文件所在目录下查找该头文件。
#include "myHeader.h"
2.C语言头文件
头文件 | 描述 |
---|---|
#include<stdio.h> | 包含输入输出常用函数,如printf、scanf、fprintf、fscanf等。 |
#include<stdlib.h> | 包含常用的标准库函数,如malloc、free、exit、atoi等。 |
#include<string.h> | 包含字符串处理函数,如strcpy、strcat、strlen等。 |
#include<math.h> | 包含常用的数学函数,如sin、cos、sqrt、ceil等。 |
#include<time.h> | 包含日期和时间函数,如time、ctime、gmtime等。 |
#include<ctype.h> | 包含字符处理函数,如isalnum、isalpha、isdigit等。 |
#include<stdbool.h> | 包含布尔变量类型。 |
#include<limits.h> | 包含整型变量的范围限制。 |
#include<float.h> | 包含浮点型变量的范围限制。 |
3.C++常用头文件
头文件 | 描述 |
---|---|
#include<iostream> | C++标准输入输出流,包含了输入输出相关的函数和对象,如cin、cout、cerr、clog等。 |
#include<string> | 包含字符串处理函数,如substr、size、length等。 |
#include<cstdlib> | 包含C++标准库的通用函数,如stdlib库中的malloc和free函数、字符串处理函数等。 |
#include<cctype> | 包含字符处理函数,如isalpha、isdigit等。 |
#include<cmath> | 包含数学函数,如sin、cos、sqrt、ceil等。 |
#include<vector> | 定义了vector类,支持动态数组操作。 |
#include<algorithm> | 包含STL(标准模板库)算法函数,如sort、max_element、min_element等。 |
#include<map> | 定义了map类,支持快速查找、插入、删除等操作。 |
#include<set> | 定义了set类,支持快速查找、插入、删除等操作。 |
#include<fstream> | C++文件输入输出流,支持文本和二进制文件的读写操作。 |