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_

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM