首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

編寫跨平台 C 函數實戰:以清屏與休眠為例

     編輯:關於C

核心思想:條件編譯 + 宏抽象

不同編譯器預定義宏不同(__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) —— 統一毫秒接口

平台頭文件原生函數單位
Windowswindows.hSleep毫秒
Linux/macOSunistd.hsleep秒
Linux/macOSunistd.husleep微秒
#if defined(__GNUC__)
    #include 
    #define SleepMs(ms) usleep((ms) * 1000)
#elif defined(_MSC_VER)
    #include 
    #define SleepMs(ms) Sleep(ms)
#endif

注意:GCC 宏連接符 ## 後不能接運算符,故用乘法展開;MSVC 支持 ## 後接表達式。

四、綜合 Demo:擲骰子小遊戲

#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;
}

五、_MSC_VER 版本號對照表

Visual Studio_MSC_VER
VS 20221930
VS 20191920
VS 20171910
VS 20151900
VS 20131800
VS 20121700
VS 20101600
VS 20081500
VS 20051400
VS 6.01200

六、最佳實踐總結

  1. 將平台差異隔離在 platform.h 中,業務代碼只調用統一宏/函數
  2. 優先使用 C 標準庫(system、sleep 等)實現跨平台,必要時才用原生 API
  3. 宏定義加括號:#define SleepMs(ms) usleep((ms)*1000) 防止參數為表達式時優先級錯誤
  4. 持續集成中配置多平台編譯(GitHub Actions: ubuntu-latest, windows-latest, macos-latest)

總結

跨平台 C 編程的精髓是「接口統一,實現隔離」。善用預定義宏、條件編譯、宏函數,即可在保持代碼整潔的前提下屏蔽 Windows/Linux/macOS 的差異。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved