Compiling and Linking GTK 3 with C project on Ubuntu

18,175

You should compile with source file appearing before the libraries as gcc hello.c $(pkg-config --cflags --libs gtk+-3.0) -o hello, the reason being the behavior of linker i.e it does not link the libraries unless the symbols of that library is seen prior in compilation.
Hope this helps!

Share:
18,175
Anwar
Author by

Anwar

Updated on June 05, 2022

Comments

  • Anwar
    Anwar almost 2 years

    I believe this is not a duplicate question, I have seen all questions/answers before I post this question. I think I have a different situation here.

    I use Ubuntu 12.04 and downloaded GTK 2 and 3. I have copied a simple GTK source code from GNOME's website. But when I use this command in terminal:

    gcc `pkg-config --cflags --libs gtk+-3.0`  hello.c -o hello
    

    I get this:

    hello.c:(.text+0x17): undefined reference to `gtk_init'
    hello.c:(.text+0x23): undefined reference to `gtk_window_new'
    hello.c:(.text+0x47): undefined reference to `gtk_main_quit'
    hello.c:(.text+0x5b): undefined reference to `g_signal_connect_data'
    hello.c:(.text+0x67): undefined reference to `gtk_widget_show'
    hello.c:(.text+0x6c): undefined reference to `gtk_main'
    

    here is my code:

    #include <gtk/gtk.h>
    
    int
    main (int   argc,
    char *argv[])
    {
      GtkWidget *window;
    
      gtk_init (&argc, &argv);
    
      window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    
      g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);
    
      gtk_widget_show (window);
    
      gtk_main ();
    
      return 0;
    }
    

    I'm not sure if errors appear because I have two versions of GTK+ or what. I'm extremely newbie in Applications Development in Ubuntu/Linux.

  • Admin
    Admin almost 12 years
    +1, exactly! Quite odd and nerving behavior of newer GCC/binutils versions.
  • another.anon.coward
    another.anon.coward almost 12 years
    @H2CO3: Yes sir(/madam)! And it is quite popular question on SO too :)
  • Rogelio Prieto
    Rogelio Prieto over 4 years
    this syntax works too: gcc hello.c `pkg-config --cflags --libs gtk+-3.0` -o hello