C/C++預先處理指令#define,條件編譯#ifdefine

來源:互聯網
上載者:User

標籤: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;}#endifint put(){    cput();    return 0;}int main(){    cput();    put();    cout << "Hello World!" << endl;    return 0;}

這次編譯通過運行成功;因為在展開put.h中包含的cput.h,會不生效,前面已經定義了宏_CPUT_H_

 

C/C++預先處理指令#define,條件編譯#ifdefine

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.