文件包含命令#include
-
调用方式
#include <头文件名> #include "头文件名" - 尖括号表示在包含文件目录中去查找 - 双引号在当前的源文件目录中查找
宏定义#define
利于代码重用,只是一种简单代换
-
无参宏定义
/*无参宏的宏名后不带参数*/ #define 标识符 字符串 #define PI 3.1415926 /*字符串处理方式*/ #define DEMO (x*x*x+2*x)
注意事项:
① 末尾多加一个";"分号也会整体替换。
② 宏定义预处理程序对它不做任何检查,被编译后被宏展开后的源程序检测。
③ 写在函数外,其作用域到源程序结束,若提前终止作用域可用#undef命令。
④ 若宏名被引号括起来,则不作代换。
⑤ 允许嵌套。
⑥ 可大写,可小写。
-
带参宏定义
#include<stdio.h> #define MAX(a,b) (a>b)?a:b int main() { int x, y, max; printf("input two numbers: "); scanf("%d%d", &x, &y); max = MAX(x, y); printf("max=%d\n", max); return 0; } /* input two numbers: 5 10 max=10 */
-
典型的宏定义重要概念
-
数值宏常量
#define PI 3.14
-
字符串宏常量
#defin PATH E:\\demo\\code\\c\\package
-
用define宏定义注释符号
#define BSC //
-
用define宏定义表达式
#define SEC_A_YEAR (60*60*244*365) UL
-
条件编译
-
第一种形式
#ifdef 标识符 程序段1 #else 程序段2 #endef /*如果标识符已被#define命令定义过则对程序段1进行编译,否则程序段2*/
-
第二种形式
#ifndef 标识符 程序段1 #else 程序段2 #endef /*功能与第一种形式相反*/
-
第三种形式
#if 常量表达式 程序段1 #else 程序段2 #endef /*若常量表达式的值为真(0),则对程序段1进行编译,否则2*/
-
Turbo C编译
#ifdef TURBOC ...//采用Turbo C标准编译 #endef #ifdef MSC ...//采用MSC标准编译 #endef