码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-17 20:22:01      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:hello   back   gpo   c中   重要   pos   int   包含   文件   

本文主要记录了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_

 

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

标签:hello   back   gpo   c中   重要   pos   int   包含   文件   

原文地址:https://www.cnblogs.com/flowingwind/p/8304668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!