在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.
廣告