標籤: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