温馨提示×

C语言中disp函数的跨平台兼容性

小樊
81
2024-09-05 19:01:58
栏目: 编程语言

在C语言中,disp 函数并不是一个标准库函数

为了实现跨平台兼容性,你可以使用条件编译来根据不同的操作系统选择合适的函数。例如:

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

这个示例代码在 Windows 上使用 MessageBoxA,在 macOS 上使用 CFUserNotificationDisplayNotice,在其他 Unix 系统(如 Linux)上使用 GTK+ 库。当然,这只是一个简单的示例,实际应用中可能需要更复杂的处理。

0