tags:

views:

311

answers:

1

I am writing an application in C++ with using GTK+ (not gtkmm) so I need to compile using g++ compiler. Is it possible to compile GTK+ applications with the g++ compiler? Are GTK+ and libraries compatible with g++ compiler?

I am trying to embed GTK+ functions call in a class like follows:

#include <gtk/gtk.h>
class LoginWindow
{
    public:
    LoginWindow();
    void on_window_destroy( GtkObject *object, gpointer user_data);

    private:

    GtkBuilder      *builder;
    GtkWidget       *window;
};

LoginWindow::LoginWindow()
{
    builder = gtk_builder_new ();
    gtk_builder_add_from_file (builder, "login_window.glade", NULL);
    window  = GTK_WIDGET (gtk_builder_get_object (builder, "login_window"));
    gtk_builder_connect_signals (builder, NULL);

    g_signal_connect( GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(on_window_destroy), NULL );
    g_object_unref (G_OBJECT (builder));
    gtk_widget_show (window);
}

void LoginWindow::on_window_destroy (GtkObject *object, gpointer user_data)
{
    gtk_main_quit ();
}

int main (int argc, char *argv[])
{
    gtk_init (&argc, &argv);

    LoginWindow loginWindow;

    gtk_main ();
    return 0;
}

Am I doing it right? I am getting compile error on line:

g_signal_connect( GTK_OBJECT(window), "destroy", GTK_SIGNAL_FUNC(on_window_destroy), NULL );

login_window.cpp: In constructor "LoginWindow::LoginWindow()":
login_window.cpp:27: error: invalid use of member (did you forget the "&" ?)

What is the right way of doing it?

+3  A: 

Gtk+ is a C-based library, so you can't give it class-member-functions as callbacks. Either define C-style functions as callbacks i.e.

extern "C"
void on_window_destroy( GtkObject *object, gpointer user_data)
{
  // do yer stuff.. keep in mind, there's no this-pointer here, it's not
  // associated with an object
}

outside of any class declarations. When registering the signal, you might want to add the LoginWindow-object itself as user_data and simply cast it when entering the method and forward the call, like so

extern "C"
void on_window_destroy( GtkObject *object, gpointer user_data)
{
  static_cast<LoginWindow*>(user_data)->on_window_destroy();
}

If you want to do it c++ style though, have a look at gtkmm, which is the c++ wrapper for Gtk+, and it'll give you a lot more OOP for your buck. It's a little more messy to work with signals/callbacks in gtkmm, but it's type safe and will save you a lot of headaches in the end.

roe