本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路。 本文已参与 ⌈新人创作礼⌋ 活动,一起开启掘金创作之路。
十四、C语言预处理指令
C语言预处理指令包括三种:
文件:以#include格式包含的文件复制到编译的源文件中,可以是头文件,也可以是其他程序文件。
宏定义:以#define定义的宏,#undef删除的宏。
条件编译:根据#ifdef和#ifndef后面的条件决定需要编译的代码。
无参数的宏:
#define pi 3.1415926;
带参数的宏:
#define MAX(x,y) ((x)>(y)?(x):(y))
条件编译:
#indef 标识符
程序1;
#else
程序2;
#endif
如果#ifdef后面的标识符已被定义过,则对“程序段1”进行编译;如果没有定义标识符,则编译“程序段2”。一般不使用#else及后面的“程序2”。
#define LINUX
int main()
{
#ifdef LINUX
printf("这是LINUX操作系统。\n");
#else
printf("未知的操作系统。");
#endif
}
#ifndef 标识符
程序1;
#else
程序2;
#endif
如果未定义标识符,则编译“程序段1”;否则编译“程序段2”。在实际开发中,程序员用#ifndef来防止头文件被重复包含。
#ifndef _PUBLIC_H
#define _PUBLIC_H 1
int strtotime(const char *strtime,time_t *ti);
#endif
#undef:取消已定义的标识符
十五、系统错误
C语言中全局变量errno,存放了函数调用过程中产生的错误码。
strerror函数声明:
//strerror
char *strerror(int errno);
strerror()用来依参数errno 的错误代码来查询其错误原因的描述字符串,然后将该字符串指针返回。
#include <stdio.h>
#include <string.h>
int main()
{
int errorno;
for(errorno=0;errorno<132;errorno++)
{
printf("%d:%s\n",errorno,strerror(errorno));
}
}
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main()
{
FILE *fp=0; // 定义文件指针变量fp
// 以只读的方式打开文件/tmp/book1.c
if ( (fp=fopen("/tmp/book1.c","r")) == 0 )
{
printf("打开文件/tmp/book1.c失败(%d:%s)。\n",errno,strerror(errno));
}
// 关闭文件
if ( fp!=0 ) fclose(fp);
return 0;
}