Basic Linux Graphics Programming

I have been using C for many years, and OpenGL as a graphics toolkit for many different languages during that time, but am only just dipping my toes into alternative modern Linux GUI toolkits by trying out GTK+ and the Cairo graphics toolkit. To be honest for the last five or six years if I have needed a GUI I have used Java, it just works for me but your mileage may vary. Anyhow, to get the necessary header files that you need so that you can do development you should (assuming a Debian or Ubuntu oriented install) execute the following command:
sudo apt-get install libgtk2.0-dev
Which will install the development libraries and any supplemental tools that are required. This also assumes (again on Debian or Ubuntu at least) that you have also previously done a:
sudo apt-get install build-essential
To get some compilers and suchlike. From here all we need to do is write a simple C program, like the following:
 
#include <gtk/gtk.h>

int main( int argc, char *argv[])
{
  GtkWidget *window;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(window), "Center");
  gtk_window_set_default_size(GTK_WINDOW(window), 230, 150);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_widget_show(window);

  g_signal_connect_swapped(G_OBJECT(window), "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  gtk_main();

  return 0;
}
 
Save the code as gtksimple.c and open a terminal into the directory where your src is saved and execute:
 
gcc -o gtksimple gtksimple.c `pkg-config --libs --cflags gtk+-2.0`
 
Now execute the code with the following (assuming that you are still in the directory where you just created your executable);
 
./gtksimple
 
and you should get something like the following:
Media_httpwwwstrangea_japhp
  A good place to go to build on this with more windowing functionality is the GTK+ tutorial and for more drawing functionality the Cairo Graphics tutorial, both over at Zetcode.
Posted
Views
​