This post was originally published on December 8, 2010. The original can be found here.

Note that while you can still write GTK+ applications on Linux using Objective-C as outlined in this post you may want to check out my little project CoreGTK which makes the whole experience a lot nicer 🙂

As sort of follow-up-in-spirit to my older post I decided to share a really straight forward way to use Objective-C to build GTK+ applications.

Objective-what?

Objective-C is an improvement to the iconic C programming language that remains backwards compatible while adding many new and interesting features. Chief among these additions is syntax for real objects (and thus object-oriented programming). Popularized by NeXT and eventually Apple, Objective-C is most commonly seen in development for Apple OSX and iOS based platforms. It ships with or without a large standard library (sometimes referred to as the Foundation Kit library) that makes it very easy for developers to quickly create fast and efficient programs. The result is a language that compiles down to binary, requires no virtual machines (just a runtime library), and achieves performance comparable to C and C++.

Marrying Objective-C with GTK+

Normally when writing a GTK+ application the language (or a library) will supply you with bindings that let you create GUIs in a way native to that language. So for instance in C++ you would create GTK+ objects, whereas in C you would create structures or ask functions for pointers back to the objects. Unfortunately while there used to exist a couple of different Objective-C bindings for GTK+, all of them are quite out of date. So instead we are going to rely on the fact that Objective-C is backwards compatible with C to get our program to work.

What you need to start

I’m going to assume that Ubuntu will be our operating system for development. To ensure that we have what we need to compile the programs, just install the following packages:

gnustep-core-devel libgtk2.0-dev

As you can see from the list above we will be using GNUstep as our Objective-C library of choice.

Setting it all up

In order to make this work we will be creating two Objective-C classes, one that will house our GTK+ window and another that will actually start our program. I’m going to call my GTK+ object MainWindow and create the two necessary files: MainWindow.h and MainWindow.m. Finally I will create a main.m that will start the program and clean it up after it is done.

Let me apologize here for the poor code formatting; apparently WordPress likes to destroy whatever I try and do to make it better. If you want properly indented code please see the download link below.

MainWindow.h

In the MainWindow.h file put the following code:

#import <gtk/gtk.h>

#import <Foundation/NSObject.h>

#import <Foundation/NSString.h> //A pointer to this object (set on init) so C functions can call

//Objective-C functions

id myMainWindow; /*

* This class is responsible for initializing the GTK render loop

* as well as setting up the GUI for the user. It also handles all GTK

* callbacks for the winMain GtkWindow.

*/

@interface MainWindow : NSObject

{

//The main GtkWindow

GtkWidget *winMain;

GtkWidget *button;

} /*

* Constructs the object and initializes GTK and the GUI for the

* application.

*

* *********************************************************************

* Input

* *********************************************************************

* argc (int *): A pointer to the arg count variable that was passed

* in at the application start. It will be returned

* with the count of the modified argv array.

* argv (char *[]): A pointer to the argument array that was passed in

* at the application start. It will be returned with

* the GTK arguments removed.

*

* *********************************************************************

* Returns

* *********************************************************************

* MainWindow (id): The constructed object or nil

* arc (int *): The modified input int as described above

* argv (char *[]): The modified input array modified as described above

*/

-(id)initWithArgCount:(int *)argc andArgVals:(char *[])argv; /*

* Frees the Gtk widgets that we have control over

*/

-(void)destroyWidget; /*

* Starts and hands off execution to the GTK main loop

*/

-(void)startGtkMainLoop; /*

* Example Objective-C function that prints some output

*/

-(void)printSomething; /*

********************************************************

* C callback functions

********************************************************

*/ /*

* Called when the user closes the window

*/

void on_MainWindow_destroy(GtkObject *object, gpointer user_data); /*

* Called when the user presses the button

*/

void on_btnPushMe_clicked(GtkObject *object, gpointer user_data); @end

MainWindow.m

For the class’ actual code file fill it in as show below. This class will create a GTK+ window with a single button and will react to both the user pressing the button, and closing the window.

#import “MainWindow.h” /*

* For documentation see MainWindow.h

*/ @implementation MainWindow -(id)initWithArgCount:(int *)argc andArgVals:(char *[])argv

{

//call parent class’ init

if (self = [super init]) { //setup the window

winMain = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (winMain), “Hello World”);

gtk_window_set_default_size(GTK_WINDOW(winMain), 230, 150); //setup the button

button = gtk_button_new_with_label (“Push me!”); gtk_container_add (GTK_CONTAINER (winMain), button); //connect the signals

g_signal_connect (winMain, “destroy”, G_CALLBACK (on_MainWindow_destroy), NULL);

g_signal_connect (button, “clicked”, G_CALLBACK (on_btnPushMe_clicked), NULL); //force show all

gtk_widget_show_all(winMain);

} //assign C-compatible pointer

myMainWindow = self; //return pointer to this object

return self;

} -(void)startGtkMainLoop

{

//start gtk loop

gtk_main();

} -(void)printSomething{

NSLog(@”Printed from Objective-C’s NSLog function.”);

printf(“Also printed from standard printf function.

”);

} -(void)destroyWidget{ myMainWindow = NULL; if(GTK_IS_WIDGET (button))

{

//clean up the button

gtk_widget_destroy(button);

} if(GTK_IS_WIDGET (winMain))

{

//clean up the main window

gtk_widget_destroy(winMain);

}

} -(void)dealloc{

[self destroyWidget]; [super dealloc];

} void on_MainWindow_destroy(GtkObject *object, gpointer user_data)

{

//exit the main loop

gtk_main_quit();

} void on_btnPushMe_clicked(GtkObject *object, gpointer user_data)

{

printf(“Button was clicked

”); //call Objective-C function from C function using global object pointer

[myMainWindow printSomething];

} @end

main.m

To finish I will write a main file and function that creates the MainWindow object and eventually cleans it up. Objective-C (1.0) does not support automatic garbage collection so it is important that we don’t forget to clean up after ourselves.

#import “MainWindow.h”

#import <Foundation/NSAutoreleasePool.h> int main(int argc, char *argv[]) { //create an AutoreleasePool

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //init gtk engine

gtk_init(&argc, &argv); //set up GUI

MainWindow *mainWindow = [[MainWindow alloc] initWithArgCount:&argc andArgVals:argv]; //begin the GTK loop

[mainWindow startGtkMainLoop]; //free the GUI

[mainWindow release]; //drain the pool

[pool release]; //exit application

return 0;

}

Compiling it all together

Use the following command to compile the program. This will automatically include all .m files in the current directory so be careful when and where you run this.

gcc `pkg-config –cflags –libs gtk+-2.0` -lgnustep-base -fconstant-string-class=NSConstantString -o “./myprogram” $(find . -name ‘*.m’) -I /usr/include/GNUstep/ -L /usr/lib/GNUstep/ -std=c99 -O3

Once complete you will notice a new executable in the directory called myprogram. Start this program and you will see our GTK+ window in action.

If you run it from the command line you can see the output that we coded when the button is pushed.

Wrapping it up

There you have it. We now have a program that is written in Objective-C, using C’s native GTK+ ‘bindings’ for the GUI, that can call both regular C and Objective-C functions and code. In addition, thanks to the porting of both GTK+ and GNUstep to Windows, this same code will also produce a cross-platform application that works on both Mac OSX and Windows.

Source Code Downloads

Source Only Package File name: objective_c_gtk_source.zip File hashes: Download Here File size: 2.4KB File download: Download Here

Originally posted on my personal website here.