Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

การเขียนโค้ด C/C++ ที่เป็นอิสระจาก OS (OS Independent)


โปรแกรมที่สามารถโต้ตอบกับระบบปฏิบัติการได้ไม่ว่าจะรันบน OS ใด

Compiler ส่วนใหญ่ของ C/C++ มีความสามารถในการ define macros ที่ตรวจจับ OS

Macros ของ GCC compiler บางตัว −

  • _WIN32: macros สำหรับ Windows 32-bit และ 64-bit

  • _WIN64: macros สำหรับ Windows 64-bit

  • _UNIX: macros สำหรับ UNIX OS

  • _APPLE_: macros สำหรับ macOS

จาก macros ที่กำหนดไว้ มาสร้างโปรแกรมที่ทำงานได้ทุก OS −

ตัวอย่าง

#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.