Objective-C Programming/Getting Started

From Wikibooks, open books for an open world
< Objective-C Programming
Jump to: navigation, search

[edit] Objective C files

In objective C, files normally use the extension .m.

These objective C files are text files that contain instructions on how to write a program. For example, this is a minimal hello world program:

#import <stdio.h>
 
int main (void)
{
        printf ("Hello world!\n");
}

A C programmer may immediately see a slight difference in the preprocessor directive. This will be described in more detail in the syntax of Objective C.

[edit] GCC

GCC, a collection of various GNU compilers, has an Objective-C package. If it is installed properly, you should be able to link against the objective-C runtime library; otherwise, you will have to consult your package system to reinstall the compiler library.

To build programs under GCC, you need to specify at least one input file and link your program against the Objective-C library:

gcc hello.m -lobjc

You might want to use additional flags to let the compiler point out common mistakes and suppress warnings about the #import keyword:

gcc -std=c99 -pedantic -Wall -Wextra -Wno-import -lobjc -o hello hello.m

Any additional files or libraries required for the program will need to be added to the command line. In addition, gcc allows compiling Objective-C files into intermediate files, which can then be linked into an output binary:

gcc -c hello.m -o hello.o
gcc hello.o -o hello

To use the object-oriented features of objective-C, you need to place the following code at the top of the file:

#import <objc/Object.h>

[edit] Other compilers

In general, the compiler name used is objc unless specified otherwise by your compiler.

In a general case, you need to have the following at the top to support objects:

#import <Object.h>
Personal tools
Namespaces

Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export