溫馨提示×

C語言中disp函數(shù)的跨平臺兼容性

小樊
81
2024-09-05 19:01:58
欄目: 編程語言

在C語言中,disp 函數(shù)并不是一個(gè)標(biāo)準(zhǔn)庫函數(shù)

為了實(shí)現(xiàn)跨平臺兼容性,你可以使用條件編譯來根據(jù)不同的操作系統(tǒng)選擇合適的函數(shù)。例如:

#include<stdio.h>

#if defined(_WIN32) || defined(_WIN64)
    #include<windows.h>
    void disp(const char *str) {
        MessageBoxA(NULL, str, "Message", MB_OK);
    }
#elif defined(__APPLE__) && defined(__MACH__)
    #include <CoreFoundation/CoreFoundation.h>
    void disp(const char *str) {
        CFStringRef message = CFStringCreateWithCString(kCFAllocatorDefault, str, kCFStringEncodingUTF8);
        CFUserNotificationDisplayNotice(0, kCFUserNotificationNoteAlertLevel, NULL, NULL, NULL, CFSTR("Message"), message, NULL);
        CFRelease(message);
    }
#else
    #include <gtk/gtk.h>
    void disp(const char *str) {
        gtk_init(NULL, NULL);
        GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "%s", str);
        gtk_dialog_run(GTK_DIALOG(dialog));
        gtk_widget_destroy(dialog);
        while (gtk_events_pending()) {
            gtk_main_iteration();
        }
    }
#endif

int main() {
    disp("Hello, World!");
    return 0;
}

這個(gè)示例代碼在 Windows 上使用 MessageBoxA,在 macOS 上使用 CFUserNotificationDisplayNotice,在其他 Unix 系統(tǒng)(如 Linux)上使用 GTK+ 庫。當(dāng)然,這只是一個(gè)簡單的示例,實(shí)際應(yīng)用中可能需要更復(fù)雜的處理。

0