Noeud:Objective C, Noeud « Next »:C++, Noeud « Previous »:How GCC Deals With languages, Noeud « Up »:Integrated Languages
There isn't too much to know about compiling Objective C sources;
you must ensure that you link the program with the libobjc.a
using -lobjc
. Here's a few sources continuing the 'Hello,
world!' theme - the first source file is main.m
:
/* main.m */ #include "HelloWorld.h" int main() { id helloWorld; helloWorld = [HelloWorld new]; [helloWorld world]; return 0; }
And the header file containing the interface for the HelloWorld
class:
/* HelloWorld.h */ #ifndef _HI_WORLD_INCLUDED #define _HI_WORLD_INCLUDED #include <objc/Object.h> #define world_len 13 @interface HelloWorld : Object { char helloWorld[world_len]; } - world; @end #endif
And finally, the implementation of HelloWorld
:
/* HelloWorld.m */ #include "HelloWorld.h" @implementation HelloWorld - world { strcpy(helloWorld, "Hello, world!"); printf("%s\n", helloWorld); } @end
Compiling this using the command
gcc -lobjc -lpthread -o helloWorld main.m HelloWorld.m
creates the executable helloWorld
which, as you can predict,
prints out the message "Hello, world!". You can use all the standard
compilation options already described to compile Objective C
programs.
- NOTE
- You'll notice that I added
-lpthread
too. I did this, because if I didn't, the following errors popped up:/usr/lib/gcc-lib/i486-suse-linux/2.95.2/libobjc.a (thr-posix.o): In function `__objc_init_thread_system': thr-posix.o(.text+0x41): undefined reference to `pthread_key_create' /usr/lib/gcc-lib/i486-suse-linux/2.95.2/libobjc.a (thr-posix.o): ... In function `__objc_mutex_trylock': thr-posix.o(.text+0x1f1): undefined reference to `pthread_mutex_trylock' collect2: ld returned 1 exit statusThis is because without the
-lpthread
flag, a number of references from the archivelibobjc.a
could not be resolved, so we had to explicitly call in thepthread
objects.