c语言一般提供三种预处理功能:宏处理、文件包含、条件编译。头文件防卫式申明中会用到条件编译中
#ifndef
#define
#endif
一般情况下,在生成可执行文件的过程中,源程序文件中的所有代码行都进行编译,但是在一些跨操作系统的情况下,要求代码既能在
Windows
Linux
条件编译的几种格式
格式 1代码语言:javascript代码运行次数:0运行复制<pre class="brush:php;toolbar:false;">#ifdef 标识符 程序段代码1#else 程序段代码2#endif
作用:当标识符被定义过,则对程序段代码 1 进行编译,否则对程序段 2 进行编译。
平时,在进行程序调试过程中,需要输出一些信息方便调试,在调试结束后,不需要这些信息输出,我们可以这样处理:
立即学习“C语言免费学习笔记(深入)”;
代码语言:javascript代码运行次数:0运行复制<pre class="brush:php;toolbar:false;">#define DEBUG//然后在代码中需要输出调试信息的地方,写一些输出信息,例如:#ifdef DEBUG printf("调试需要输出的提示信息\n");#endif<pre class="brush:php;toolbar:false;">#ifndef 标识符 程序段代码 1 #else 程序段代码 2#endif
作用:若标识符未被定义,则编译程序段代码 1,否则编译程序段代码 2。与格式 1 正好相反,
RELEASE
DEBUG
<pre class="brush:php;toolbar:false;">#define RELEASE//然后在代码中需要输出调试信息的地方,写一些输出信息,例如:#ifndef RELEASE printf("调试需要输出的提示信息\n");#endif<pre class="brush:php;toolbar:false;">#if 表达式 程序段代码 1#else if 表达式2 程序段代码 2#else 程序段代码 3#endif
跨平台项目开发,采用条件编译可以同同一套代码在不修改代码的情况下在
Windows
Linux
<pre class="brush:php;toolbar:false;">if __Linux__ //Linux专有函数代码#elif _Win32 //windows专有函数代码#else //其他平台专有函数代码#endif
在多文件包含的情况下,有些变量何你可能被直接的或者间接的重复定义,重复
#include
#ifndef
#define
#endif
范例:
头文件 head1.h 有如下定义:代码语言:javascript代码运行次数:0运行复制<pre class="brush:php;toolbar:false;">int g_head1 = 1;
<pre class="brush:php;toolbar:false;">int g_head2 = 2;
g_head1
g_head2
<pre class="brush:php;toolbar:false;">#include "head1.h"#include "head2.h"#include <iostream>using namespace std;int main(){ cout<<g_head1<<endl; //1 cout<<g_head2<<endl; //2 return 0;}head2.h
head1.h
head2.h
<pre class="brush:php;toolbar:false;">#include "head1.h";int g_head2 = 2;

此时编译就会出现重复定义的错误,这是因为源文件.cpp 包含了头文件
head1.h
head2.h"
head2.h
head1.h
head1.h
g_head1
head1.h
<pre class="brush:php;toolbar:false;">#ifndef _HEAD1_#define _HEAD1_int g_head1 = 1;#endif
head2.h
<pre class="brush:php;toolbar:false;">#ifndef _HEAD2_#define _HEAD2_#include "head1.h"int g_head2 = 2;#endif

修改后再次编译,通过并成功执行,使用
#ifndef
#define
#endif
include
更多案例可以go公众号:C语言入门到精通
以上就是C语言头文件防卫式声明的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号