Search code examples
cgtkheader-files

Include GTK in header file or implementation


My header makes declaration of GtkWidget pointers.

// header file    
GtkWidget   *equalButton;
GtkWidget   *pointButton;
GtkWidget   *modeButton;

And the implementation (.c) file is going to bind them to glade objects using GtkBuilder.

Where should I put #include<gtk/gtk.h> to make code reasonable?


Solution

  • I suggest you to do the following (here I'm using a Hello World kind of project as an example):

    Header file (components.h)

    #include <gtk/gtk.h>
    
    // declarations
    extern GtkWidget *label_hello;
    
    extern void on_btn_hello_clicked();
    extern void on_window_main_destroy();
    

    C file (components.c)

    #include "components.h"
    
    // definition
    GtkWidget *label_hello;
    
    void on_btn_hello_clicked()
    {
        ...
        gtk_label_set_text(GTK_LABEL(label_hello), "Hello, world!");
        ...
    }
    
    void on_window_main_destroy()
    {
        gtk_main_quit();
    }
    

    Main file (main.c)

    #include "components.h"
    
    int main(int argc, char *argv[])
    {
         ...
         GtkBuilder *builder;
         builder = gtk_builder_new();
         gtk_builder_add_from_file (builder, "glade/window_main.glade", NULL);
    
         window = GTK_WIDGET(gtk_builder_get_object(builder, "window_main"));
    
         ...
    
         label_hello = GTK_WIDGET(gtk_builder_get_object(builder, "lbl_hello"));
    
         ...    
    }
    

    Note: The builder can be initialized in a function of a .c file and then the pointer can be passed around across the different functions of your code. It pretty much depends on how you want to build your code. In the above example the builder is in the main.c file, but it can easily be moved to the components.c file. For instance, you could do something like:

    GtkBuilder *get_builder_instance(){
    
        GtkBuilder * builder = malloc(sizeof(GtkBuilder));
        builder = gtk_builder_new();
        gtk_builder_add_from_file (builder, "glade/window_main.glade", NULL);
    
        return builder;
    }