在C/C++中編寫與作業系統無關的程式碼


一個能夠與作業系統互動的程式,無論它執行在哪個作業系統上。

大多數c/c++編譯器都有定義宏以檢測作業系統的功能。

GCC編譯器的一些宏是 −

  • _WIN32: 32位和64位Windows作業系統的宏。

  • _WIN64: 64位Windows作業系統的宏。

  • _UNIX: UNIX作業系統的宏。

  • _APPLE_: macOS的宏。

基於這些已定義的宏,讓我們建立一個與作業系統無關的程式 −

示例

 線上演示

#include <iostream>
using namespace std;
int main() {
   #ifdef _WIN32
      system("dir");
   #else
      system("ls");
   #endif
      return 0;
}

輸出

This lists all files of the directory to the output screen irrespective of OS.

更新時間: 2020年4月17日

317次瀏覽

開啟你的職業生涯

完成教程即可獲得認證

開始
廣告