Home > Articles > Programming > C/C++

Programming in Objective-C

  • Print
  • + Share This
  • 💬 Discuss
Learn how to write your first Objective-C program.
This chapter is from the Rough Cut version of the book.

In this chapter we'll dive right in and show you how to write your first Objective-C program. You won't work with objects just yet; that is the topic of the next chapter. We want you to understand the steps involved in keying in a program and compiling and running it. Special attention is given to this process under Windows and on a Macintosh computer.

To begin, let's pick a rather simple example—a program that displays the phrase Programming is fun! on your screen. Without further ado, here is an Objective-C program to accomplish this task.

Example 2.1.

// First program example

#import Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSLog (@"Programming is fun!");

   [pool drain];
   return 0;
}

Compiling and Running Programs

Before we go into a detailed explanation of this program, let's learn the steps involved in compiling and running it. You can both compile and run your program using Xcode or you can use the GNU Objective-C compiler in a Terminal window [1] . Let's go through the sequence of steps using either method. Then, you can decide how you want to work with your programs throughout the rest of this book.

Using Xcode

Xcode is a sophisticated application that allows you to easily type in, compile, debug, and execute programs. If you plan on doing serious application development on the Mac, learning how to use this powerful tool is worthwhile. We'll just get you started here. Later, we'll return to Xcode and take you through the steps involved in developing a graphical application with it.

First, Xcode is located in the Developer folder inside a subfolder called Applications. Its icon is shown in Figure 2.1.

02fig01.jpg

Figure 2.1 Xcode icon.

Start Xcode. Under the File menu, select New Project (see Figure 2.2).

02fig02.jpg

Figure 2.2 Starting a new project.

A window will then appear, as shown in Figure 2.3.

02fig03.jpg

Figure 2.3 Starting a new project (cont'd).

Scroll down the the left pane until you get to "Command Line Utility." In the upper right pane, highlight "Foundation Tool" Your window should now appear as shown in Figure 2.4.

02fig04.jpg

Figure 2.4 Starting a new project (cont'd)

Click Choose.... This brings up a new window as shown in Figure 2.5.

02fig05.jpg

Figure 2.5 Xcode file list window.

Let's call the first program prog1, so type that into the Save As: field. You may want to create a separate folder to store all your projects in. On my system, I keep the projects for this book in a folder called ObjC Progs.

Click on the Save button to create your new project. This will give you a project window such as that shown in Figure 2.6 Note that your window may display differently if you've used Xcode before or have changed any of its options.

02fig06.jpg

Figure 2.6 Xcode prog1 project window.

Now it's time to type in your first program. Select the file prog1.m in the upper right pane. Your Xcode window should now appear as shown in Figure 2.7.

02fig07.jpg

Figure 2.7 File and .

Objective-C source files use .m as the last two characters of the file name (known as its extension) Other commonly used filename extensions are shown in Table 2.1.

Table 2.1. Common Filename Extensions

Extension

Meaning

.c

C language source file

.cc, .cpp

C++ language source file

.h

Header file

.m

Objective-C source file

.mm

Objective-C++ source file

.pl

Perl source file

.o

Object (compiled) file

Returning to your Xcode project window, the bottom right side of the window shows the file called prog1.m and contains the following lines:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSLog (@"Hellow World!");

   [pool drain];
   return 0;
}

(If you can't see the file's contents displayed, you may have to click and drag up the bottom right pane to get the edit window to appear. Again, this will be based upon having previously used Xcode.) You can edit your file inside this window. XCode has created a template file for you to use.

Make changes to the program shown in the Edit window to match Program 2.1. The line you add at the beginning of prog1.m that starts with two slash characters (//) is called a comment, and we'll talk more about it shortly.

Your program in the edit window should now look like this:

// First program example

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSLog (@"Programming is fun!");

   [pool drain];
   return 0;
}

Don't worry about all the colors shown for your text on your screen. Xcode indicates values, reserved words, and so on using different colors.

Now it's time to compile and run your first program—in Xcode terminology it's called build and run. You need to save your program first, however. This can be done by selecting Save from the File menu. If you try to compile and run your program without first saving your file, Xcode asks whether you want to first save your program.

Under the Build menu, you can select either Build or Build and Run. Select the latter because that automatically runs the program if it builds without any errors. You can also activate Build and Run by clicking the icon that appears in the toolbar.

If you made mistakes in your program, you'll see error messages listed during this step. In that case, go back, fix the errors, and repeat the process. After all the errors have been removed from the program, a new window appears; it's labeled prog1 – Debugger Console. This window contains the output from your program and should look similar to Figure 2.8. If this window does not automatically appear, go to the main menu bar and select Console from the Run menu. We'll discuss the actual contents of the Console window shortly.

02fig08.jpg

Figure 2.8 Xcode Debugger Console window.

You're now done with the procedural part of compiling and running your first program with Xcode (whew!). The following summarizes the steps involved in creating a new program with Xcode:

  1. Start the Xcode application
  2. If this is a new project, select File, New Project.
  3. For the type of application, select Command Line Utility, Foundation Tool and click Choose... .
  4. Select a name for your project, and optionally a directory to store your project files in. Click Save.
  5. In the top right pane you will see the file prog1.m (or whatever name you assigned to your project, followed by the characters .m. Highlight that file. Type your program into the edit window that appears directly below that pane.
  6. Save the changes you've entered by selecting File, Save.
  7. Build and run your application by selecting Build, Build and Run or by clicking the Build and Go Button.
  8. If you get any compiler errors or the output is not what you expected, make your changes to the program and repeat steps 6 and 7.

Using Terminal

Some people may wish to avoid having to learn how to use Xcode to get started programming with Objective-C. If you're used to using the Unix shell and command line tools, you may want to edit, compile, and run your programs using the Terminal application. Let's examine how to go about doing that in detail.

The first step is to start the Terminal application on your Mac. The Terminal application is located in the Applications folder, stored under Utilities. Its icon is shown in Figure 2.9.

02fig09.jpg

Figure 2.9 Terminal program icon.

Start the Terminal application, and you'll see a window that looks like Figure 2.10.

02fig10.jpg

Figure 2.10 Terminal window.

Commands are typed after the $ (or % depending on how your Terminal application is configured) on each line. If you're familiar with using Unix, this will be straightforward.

First, you need to enter the lines from Program 2.1 into a file. You can begin by creating a directory in which to store your program examples. Then, you must run a text editor, such as vi or emacs, to enter your program:

sh-2.05a$ mkdir Progs   
   Create a directory to store programs in
sh-2.05a$ cd Progs      
   Change to the new directory
sh-2.05a$ vi prog1.m    
   Start up a text editor to enter program
 ..

For Objective-C files, you can choose any name you want; just make sure the last two characters are .m. This is done out of convention, so that the compiler knows you have an Objective-C program.

After you've entered your program into a file, you can use the GNU Objective-C compiler, which is called gcc, to compile and link your program. The general format of the gcc command is

gcc –framework foundation files -o progname

The option

-framework foundation

says to use information about the Foundation framework. Just remember to use this option on your command line. files is the list of files to be compiled. In our example, we have only one such file and we're calling it prog1.m. progname is the name of the file that will contain the executable if the program compiles without any errors.

We'll call the program prog1; here then is the command line to compile your first Objective-C program:

$ gcc –framework foundation prog1.m -o prog1 Compile prog1.m & call it prog1
   
$

The return of the command prompt without any messages means that no errors were found in the program. Now you can subsequently execute the program by typing the name prog1 at the command prompt:

$ prog1        
   Execute prog1
sh: prog1: command not found
$

This is the result you'll probably get unless you've used Terminal before. The fact is that the Unix shell (which is the application running your program) doesn't know where prog1 is located. We won't get into all the details here. You have two options: One is to precede the name of the program with the characters ./ so that the shell knows to look in the current directory for the program to execute. The other is to add the directory in which your programs are stored (or just simply the current directory) to your PATH variable. Ask someone for help on how to do this if needed.

Let's take the first approach here:

$ ./prog1      
   Execute prog1
2008-06-08 18:48:44.210 prog1[7985:10b] Programming is fun!
$

That's better! If you used Terminal to compile and execute your program, you can skip the next section. However, you might want to skim this section to learn how you can also use Xcode to compile and run your programs.

  • + Share This
  • 🔖 Save To Your Account

Discussions

comments powered by Disqus