I am now learning to use GTK+3.0 with C in Linux. After reading some tutorials and sample code, I have some questions regarding how to initialize an application.
Here are two versions of code I have seen.
#include <gtk/gtk.h>
static void
activate (GtkApplication* app,
gpointer 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;
}
This code used gtk_application_new()
to init a GtkApplication
and g_application_run()
to start it.
This is the second one.
#include <gtk/gtk.h>
int main(int argc,char *argv[])
{
GtkWidget *window;
gtk_init(&argc,&argv);
window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_title(GTK_WINDOW(window),"helloworld");
gtk_widget_show(window);
gtk_main();
return 0;
}
This code used gtk_init()
to init the application and gtk_main()
to run it.
However, I can't figure out the difference between them as the running result seems the same.
gtk_init () It will initialize everything needed to operate the toolkit and parses some standard command line options. argc and argv are adjusted accordingly so your own code will never see those standard arguments.
gtk_main (); gtk_main() is another call you will see in every GTK application. When control reaches this point, GTK will sleep waiting for X events (such as button or key presses) to occur. In our simple example however, events are ignored.
The gtk_init()
function initializes internal variables used by the library, the g_application_new()
calls gtk_init()
internally, so there is no difference or similarity, they serve different purposes, it's simply that one of them, includes the other one.
I don't know this from reading the documentation or anything similar, it's just a logical conclusion.
Probably, GtkApplication
was created to avoid using global variables inside the Gtk+ library, and instead of that now you can use a GtkApplication
to hold the application wide variables in it.
So it seems like the correct way to do it, I personally like it, but it's been a while since I wrote a Gtk+ application, and it was with the version 2, so I don't know much about it.
Gtk+ has a great feature and it's that it's very well documented, just google for GtkApplication
and you will understand better what it is for, and how it should be used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With