C/C++预处理指令#define,条件编译#ifdefine

本文主要记录了C/C++预处理指令,常见的预处理指令如下:

空指令,无任何效果

include包含一个源代码文件

define定义宏

undef取消已定义的宏

if如果给定条件为真,则编译下面代码

ifdef如果宏已经定义,则编译下面代码

ifndef如果宏没有定义,则编译下面代码

elif如果前面的#if给定条件不为真,当前条件为真,则编译下面代码

endif结束一个#if……#else条件编译块

error停止编译并显示错误信息

条件编译命令最常见的形式为:

ifdef 标识符

程序段1

#else

程序段2

#endif

例:

#ifndef bool
#define ture 1
#define false 0
#endif

在早期vc中bool变量用1,0表示,即可以这么定义,保证程序的兼容性

在头文件中使用#ifdef和#ifndef是非常重要的,可以防止双重定义的错误。

//main.cpp文件

#include "cput.h"
#include "put.h"
int main()
{
    cput();
    put();
    cout << "Hello World!" << endl;
    return 0;
}
//cput.h 头文件

#include <iostream>
using namespace std;
int cput()
{
    cout << "Hello World!" << endl;
    return 0;
}
//put.h头文件

#include "cput.h"
int put()
{
    cput();
    return 0;
}

编译出错;在main.cpp中两次包含了cput.h

尝试模拟还原编译过程;

当编译器编译main.cpp时

//预编译先将头文件展开加载到main.cpp文件中

//展开#include "cput.h"内容
#include <iostream>
using namespace std;
int cput()
{
    cout << "Hello World!" << endl;
    return 0;
}

//展开#include "put.h"内容
//put.h包含了cput.h先展开
#include <iostream>
using namespace std;
int cput()
{
    cout << "Hello World!" << endl;
    return 0;
}
int put()
{
    cput();
    return 0;
}

int main()
{
    cput();
    put();
    cout << "Hello World!" << endl;
    return 0;
}

很明显合并展开后的代码,定义了两次cput()函数;

如果将cput.h改成下面形式:

#ifndef _CPUT_H_
#define _CPUT_H_
#include <iostream>
using namespace std;
int cput()
{
    cout << "Hello World!" << endl;
    return 0;
}
#endif

当编译器编译main.cpp时合并后的main.cpp文件将会是这样的:

#ifndef _CPUT_H_
#define _CPUT_H_
#include <iostream>
using namespace std;
int cput()
{
    cout << "Hello World!" << endl;
    return 0;
}
#endif

#ifndef _CPUT_H_
#define _CPUT_H_
#include <iostream>
using namespace std;
int cput()
{
    cout << "Hello World!" << endl;
    return 0;
}
#endif
int put()
{
    cput();
    return 0;
}

int main()
{
    cput();
    put();
    cout << "Hello World!" << endl;
    return 0;
}

这次编译通过运行成功;因为在展开put.h中包含的cput.h,会不生效,前面已经定义了宏CPUT_H

原文链接: https://www.cnblogs.com/flowingwind/p/8304668.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/267890

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午6:54
下一篇 2023年2月14日 下午6:55

相关推荐