Intro

We’ll have look below into how to build a minimal “Hello World” GUI app in C using GTK4. The example was built on MacOS Big Sur using CMake in CLion, but should work on any other operating systems as long as you have CMake.

Requirements

brew install pkg-config
brew install gtk+
brew install gtk4

Configure CMake

The contents of your CMakeLists.txt should look something like this:

cmake_minimum_required(VERSION 3.20)
project(HexEditor)

set(CMAKE_CXX_STANDARD 20)

find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK4 REQUIRED gtk4)

include_directories(${GTK4_INCLUDE_DIRS})
link_directories(${GTK4_LIBRARY_DIRS})

add_definitions(${GTK4_CFLAGS_OTHER})

add_executable(HexEditor main.cpp)

target_link_libraries(HexEditor ${GTK4_LIBRARIES})

The code

To create a small window with a “Hello World” label on it, you will need to start with something like this:

#include <gtk/gtk.h>

static void on_activate (GtkApplication *app) {
    // Create a new window
    GtkWidget *window = gtk_application_window_new (app);
    // Create a new button
    GtkWidget *button = gtk_button_new_with_label ("Hello, World!");
    // When the button is clicked, close the window passed as an argument
    g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_window_close), window);
    gtk_window_set_child (GTK_WINDOW (window), button);
    gtk_window_present (GTK_WINDOW (window));
}

int main(int argc, char **argv) {
    // Create a new application
    GtkApplication *app = gtk_application_new ("com.example.GtkApplication",
                                               G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (on_activate), NULL);
    return g_application_run (G_APPLICATION (app), argc, argv);
}

This example was taken from https://gtk.org/.

Hello World

Hello World