不同編譯器預定義宏不同(__GNUC__ GCC/Clang,_MSC_VER MSVC),利用 #if defined 選擇平台相關頭文件與實現,對外暴露統一接口。
#if defined(__GNUC__)
#include // sleep, usleep, system("clear")
#elif defined(_MSC_VER)
#include // Sleep, system("cls")
#endif
clear()static inline void clear(void) {
#if defined(__GNUC__)
system("clear");
#elif defined(_MSC_VER)
system("cls");
#endif
}
進階:將命令字符串提取為宏,避免重複調用 system 開銷:
#if defined(__GNUC__)
#define CLEAR_CMD "clear"
#elif defined(_MSC_VER)
#define CLEAR_CMD "cls"
#endif
// 使用時 system(CLEAR_CMD);
SleepMs(int ms) —— 統一毫秒接口| 平台 | 頭文件 | 原生函數 | 單位 |
|---|---|---|---|
| Windows | windows.h | Sleep | 毫秒 |
| Linux/macOS | unistd.h | sleep | 秒 |
| Linux/macOS | unistd.h | usleep | 微秒 |
#if defined(__GNUC__)
#include
#define SleepMs(ms) usleep((ms) * 1000)
#elif defined(_MSC_VER)
#include
#define SleepMs(ms) Sleep(ms)
#endif
注意:GCC 宏連接符 ## 後不能接運算符,故用乘法展開;MSVC 支持 ## 後接表達式。
#include#include #include /* 跨平台宏定義 */ #if defined(__GNUC__) #include #define CLEAR_CMD "clear" #define SleepMs(ms) usleep((ms)*1000) #elif defined(_MSC_VER) #include #define CLEAR_CMD "cls" #define SleepMs(ms) Sleep(ms) #endif int main() { srand((unsigned)time(NULL)); int dice[3]; char input; while (1) { system(CLEAR_CMD); printf("=== 擲骰子遊戲 ===\n"); printf("按 Enter 擲骰,q 退出:"); input = getchar(); if (input == 'q' || input == 'Q') break; while (getchar() != '\n'); // 清理緩衝區 for (int i = 0; i < 3; i++) dice[i] = rand() % 6 + 1; printf("骰子: %d %d %d\n", dice[0], dice[1], dice[2]); /* 簡單規則判斷 */ if (dice[0] == dice[1] && dice[1] == dice[2]) { printf("豹子!\n"); } else if ((dice[0]+dice[1]+dice[2]) >= 11) { printf("大\n"); } else { printf("小\n"); } SleepMs(1500); // 跨平台休眠 1.5 秒 } return 0; }
| Visual Studio | _MSC_VER |
|---|---|
| VS 2022 | 1930 |
| VS 2019 | 1920 |
| VS 2017 | 1910 |
| VS 2015 | 1900 |
| VS 2013 | 1800 |
| VS 2012 | 1700 |
| VS 2010 | 1600 |
| VS 2008 | 1500 |
| VS 2005 | 1400 |
| VS 6.0 | 1200 |
platform.h 中,業務代碼只調用統一宏/函數system、sleep 等)實現跨平台,必要時才用原生 API#define SleepMs(ms) usleep((ms)*1000) 防止參數為表達式時優先級錯誤跨平台 C 編程的精髓是「接口統一,實現隔離」。善用預定義宏、條件編譯、宏函數,即可在保持代碼整潔的前提下屏蔽 Windows/Linux/macOS 的差異。