What it is
Xlib is the standard C library for interfacing with the X Window System (X11) on Unix-like operating systems. It allows applications to create and manage windows, handle user input events, draw graphics, and communicate with the X server.
Xlib enables C programs to open a connection to the X server, create windows, manage events like keyboard and mouse inputs, and draw graphics primitives such as lines, rectangles, and text.
Installation
sudo apt install libx11-devGetting started
The smallest useful thing you can do with it, and what each part means.
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
Display *d;
Window w;
XEvent e;
int s;
d = XOpenDisplay(NULL);
if (d == NULL) {
fprintf(stderr, "Cannot open display\n");
exit(1);
}
s = DefaultScreen(d);
w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 200, 200, 1,
BlackPixel(d, s), WhitePixel(d, s));
XSelectInput(d, w, ExposureMask | KeyPressMask);
XMapWindow(d, w);
while (1) {
XNextEvent(d, &e);
if (e.type == Expose) {
XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
}
if (e.type == KeyPress)
break;
}
XCloseDisplay(d);
return 0;
}Advanced usage
Where the library earns its place over a simpler alternative.
#include <X11/Xlib.h>
// Use functions like XDrawLine, XDrawRectangle, XDrawArc to draw shapes on a window// Use XSelectInput to listen for multiple event types such as KeyPressMask, ButtonPressMask, ExposureMask
// Use XNextEvent to process events in an event loop// Use XLoadFont and XDrawString to draw text on windows with XlibErrors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Cannot open display
- Ensure the DISPLAY environment variable is set correctly and an X server is running.
- BadWindow or BadDrawable
- Verify that the window or drawable exists before performing drawing operations.
- Font loading failure
- Check that the specified font exists on the system and the name is correct.
Best practices
- Always check the return values of Xlib functions to catch errors early.
- Use event masks efficiently to avoid unnecessary event handling overhead.
- Close the Display connection using XCloseDisplay to release resources.
- Consider using higher-level toolkits like GTK or Qt for complex GUI applications.
- Separate event handling and drawing logic for maintainability.
Background
Why it exists, and what it was reacting to.
Xlib was developed in the mid-1980s as the primary client library for X11. It provides a low-level interface to X server operations, allowing developers to build graphical applications directly. Although higher-level toolkits like GTK and Qt are more commonly used today, Xlib is still valuable for lightweight, custom, or embedded X11 applications.
