• 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_

  • 相关阅读:
    C#调用Halcon
    C#跨窗体程序调用方法的具体操作
    C#调用DLL报错:试图加载格式不正确的程序
    C#窗体程序设置禁用关闭按钮
    C#窗体程序设置禁用关闭按钮
    C#在字符串中查询指定字符串是否存在
    poj1654
    poj1873
    poj2451
    poj1113
  • 原文地址:https://www.cnblogs.com/flowingwind/p/8304668.html
Copyright © 2020-2023  润新知