是的,C 语言使用 glibc 本身并不能直接打开窗口,因为 glibc 只是一个标准 C 库,提供系统调用封装、标准 I/O、内存管理等功能。它本身没有图形界面(GUI)功能。不过,在 Linux 上,你可以用 glibc + X11 或 Wayland 等图形库 来创建窗口。
下面给你一个最小的例子,使用 Xlib(X11) 在 Linux 上打开一个简单窗口。这个程序使用的 C 库是 glibc。
#include <X11/Xlib.h> #include <stdio.h> #include <stdlib.h> int main() { Display *display; Window window; XEvent event; int screen; /* 1. 打开与 X 服务器的连接 */ display = XOpenDisplay(NULL); if (display == NULL) { fprintf(stderr, "Cannot open display\n"); exit(1); } screen = DefaultScreen(display); /* 2. 创建窗口 */ window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 400, 300, 1, BlackPixel(display, screen), WhitePixel(display, screen)); /* 3. 选择要监听的事件类型 */ XSelectInput(display, window, ExposureMask | KeyPressMask); /* 4. 显示窗口 */ XMapWindow(display, window); /* 5. 事件循环 */ while (1) { XNextEvent(display, &event); if (event.type == Expose) { /* 当窗口需要重绘时 */ XFillRectangle(display, window, DefaultGC(display, screen), 20, 20, 100, 100); } if (event.type == KeyPress) break; /* 按任意键退出 */ } /* 6. 关闭连接 */ XCloseDisplay(display); return 0; }
gcc -o xwindow_example xwindow_example.c -lX11 ./xwindow_example
-lX11
如果你愿意,我可以帮你写一个 更现代、跨平台的 C + SDL2 或 GTK3 示例,在 Linux 上用 glibc 打开窗口并处理鼠标键盘事件,比 Xlib 更方便。
你想看哪种?Xlib 还是 SDL/GTK?
Github开源生信云平台 DEMO