Xlib programming: a short tutorial

I haven't found anything very satisfying on the Web as an Xlib tutorial. Many of them are too much Motif-oriented for my taste. Furthermore, I answer questions about X programming almost daily, so I've started to put together some small coursewares.

Important note:

the example programs are written in C++, but this is mainly for the ability to declare variables anywhere.

You can get this (again very short) tutorial as one tar.gz file (~ 7 Kb).


Let's begin with a short story: the eternal story of the newbie at Xlib writing his/her first program.

"Ok, I've to open a connection to the X server (whatever this means), with XOpenDisplay, then create a window with XCreateWindow, then draw a line with XDrawLine. Then, the program sleeps for ten seconds so I can see the result. Sounds easy."

The poor newbie writes the program. And nothing happens. He then calls his wizard friend.

-"Did you perform an XFlush after you've done everything ?
- No, why ?
- The requests stay in the client,"
wizard doubletalk, thinks the poor newbie, " if you don't."

The poor newbie changes the program. And nothing happens. He then calls his wizard friend.

-"Did you map your window ?
- Did I do what ???
- Creating a window doesn't make it appear on the screen. You've to map it with XMapWindow first.

The poor newbie changes the program. The window appears with nothing in it (like this). The poor newbie then calls his wizard friend.

-"Did you wait for a MapNotify before drawing your line ?" (more wizard doubletalk)
- "No, why ?
- X has a stateless drawing model, the content of the window may be lost when the window isn't on the screen."
(overflow, why can't these wizard guys speak just like you and me ?) "You've to wait for a MapNotify before drawing."

The poor newbie changes the program. Things are getting more and more complex. Not as easy as it first seemed. A loop gets the events until a MapNotify. The window appears with nothing in it. The poor newbie then calls his wizard friend.

-"I got it, did you select the StructureNotifyMask on your window ?
- ???
- Just do it, and everything'll be fine.

The poor newbie fixes the program. And the miracle happens ! A line in the window. Until now, the program looks like this (it is actually slighty more complex than the dialog may let you think).

Now you've learned at least 2 things:

Now, if you want to learn more and get a deeper understanding of the program, go to next lesson.

More about X.


Christophe Tronche, ch@tronche.com