四大核心功能
- 檔案包含:
#include
- 條件編譯:
#if, #ifdef, #ifndef, #elif, #else, #endif
- 版面控制:
#pragma
- 巨集替換:
#define, #undef
檔案包含細節
#include <header>:搜尋標準庫路徑(系統標頭)。
#include "header":先搜尋當前工作目錄,再搜尋系統路徑。
- C++ 標準標頭不帶
.h(<iostream>),舊式帶 .h(<iostream.h>)已棄用。標準庫組件置於 namespace std,支援寬字元,介面經修訂。
條件編譯常見模式
// 防重複包含(Include Guard)
#ifndef MY_HEADER_H
#define MY_HEADER_H
// ... 宣告 ...
#endif
// 版本/平台條件編譯
#if defined(_WIN32)
#include <windows.h>
#elif defined(__linux__)
#include <unistd.h>
#endif
// 編譯時開關
#ifdef DEBUG
#define LOG(fmt, ...) printf(fmt, ##__VA_ARGS__)
#else
#define LOG(fmt, ...) ((void)0)
#endif
#pragma 實用範例
#pragma once:現代編譯器支援,替代 Include Guard,更簡潔。
#pragma pack(n):控制結構體對齊(見位元組對齊文章)。
#pragma message("Compiling " __FILE__):編譯期輸出訊息。
#pragma warning(disable: 4996)(MSVC):關閉特定警告。
巨集定義進階
- 物件巨集:
#define MAX 100
- 函式巨集:
#define SQR(x) ((x)*(x))(注意副作用與括號)。
- 字串化:
#define STR(x) #x
- 黏著:
#define CAT(a,b) a##b
- 多行巨集:使用反斜線續行,或
do { ... } while(0) 包裝複合陳述句。
#undef 限制巨集作用域,避免汙染。
其他指令
#line:修改 __LINE__、__FILE__,常用於代碼產生器。
#error:編譯期報錯,阻止編譯繼續。
最佳實踐
- 巨集名稱全大寫,避免與變數衝突。
- 複雜邏輯改用
inline 函數或 constexpr(C++)。
- 條件編譯區塊保持淺層巢狀,便於閱讀。
- 善用
#pragma once 簡化標頭檔防護。