Introduction to GUI Programming in C using GTK
Advertisement
Learning a programming language is common but very few know where the language is used. What is its application? College or School only teaches us the coding part, but we should focus on the application part of the language. In this blog, I will be introducing you to Graphical User Interface (GUI) Programming in C Language using the GTK library.
Pre-requisite to GUI Programming in C
This is more of a development area and thus basics of C Language will do the work for you. But, you should have knowledge about pointers in C Language and how to implement them.
Why C for GUI?
The C Language is a low-level language and closer to the hardware, this helps us build powerful software and manage memory.
A low-level language doesn’t restrict the developer and gets the whole control over the hardware and memory management.
What is GTK?
GTK is a multi-platform toolkit that helps us create Graphical User Interfaces. GTK provides a collection of widgets and we as a developer just need to use it to create our own GUI software.
Widgets in GTK is the fundamental building block for GUI Programming. The Widgets in GTK are organized in hierarchical form.
Everything you see on the screen is widgets.
Example:
Window – The Main Container.
User-Interfaces like Buttons, Menu Bar, Drop-downs, Input Fields, etc.
In C Language, the GTK is implemented using the GObject (spelled as G-Object), an Object-Oriented framework for the C Language.
We use a library like GTK because it makes creating rich GUI easy for us with less coding involved. The library also manages the pixels of the desktop and we don’t need to create Widgets manually pixel by pixel.
Versions of GTK
There are two versions of the GTK Library, primarily GTK 2 and GTK 3. The latest stable version of GTK is v3.24.23.
In this blog, we will focus on the latest version of GTK i.e GTK 3.
Let’s create our first GTK GUI Program.
GUI Programming in C Using GTK
Let’s take a quick look at how the GUI programming looks like in C language using the GTK library.
#include <gtk/gtk.h>
static void activate (GtkApplication* app, gpointe user_data)
{
GtkWidget *window;
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Window");
gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
gtk_widget_show_all (window);
}
int main (int argc, char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
The above code is to create a window using GTK in C language.
Output:
In the next blog, we will learn how we can set up the GTK Library to use in the C library.
Hope you like it!