[Masters of the Void]
2. Our First Program

Previous | Next

You already installed Xcode in the previous step, so let's jump right in and start it up: Go into the Finder, and open the Applications sub-folder in the Developer subfolder on your hard disk. Double-click the "Xcode" icon. If this is the first time you've run Xcode, you will get a setup assistant. Go through this assistant (the defaults are OK) and once that is done, you will probably get a Welcome to Xcode window. Close it for now. Then choose New Project from the File menu.

A project is an Xcode document, and essentially a list of files that make up one program. There are different kinds of projects depending on what the final result should be. For example, you can use Xcode to create application programs, but also to create screen savers or plugins. Each kind of project needs to be assembled from different kinds of files, in a slightly different way, and an Xcode project contains the information what to compile how. Due to the sheer number of settings involved, Xcode provides pre-made project templates that are already correctly set up for common programs.

Xcode project template window

To get you started easily, we will start with a simple program that can be run using Terminal.app's command line. So, scroll down to the Command Line Utility section and choose the Standard Tool template, which will give you a very simple C program. Click Next and then type in MyFirstProgram as the project name, then click Finish.

Further Information: There are a couple dozen templates that come with Xcode, but most of them require being familiar with Carbon, Cocoa or C++, and thus are beyond the scope of this tutorial. You can also add your own templates, and some applications come with templates for developing plug-ins that will show up under their own heading in this list.

Xcode groups and files listYou will now get a window with a list labeled Groups & Files on the left, and a Details list on the right, which shows more information on whatever is selected on the left. If you look closely, you'll see that there is a split view separator at the bottom of the details list. It has a little circular "dent" in the middle. Grab that and drag up, and you will see that below the details view there is a text editor (or more likely, an empty area that says "No Editor". This is where you will edit text using Xcode. If you'd rather have several windows, leave this "dent" down there and just double-click your source file in the Groups & Files list and it will open in its own window.

The Groups & Files list contains a lot of stuff, including an icon for your project, and a few brown folders (which Xcode calls "groups"). But right now we only care about one of the three little brown folders under the "MyFirstProgram" project icon: the "Source" group. Click the triangle next to it to see that there is one file in this group: main.c. Note the file name suffix (or "extension") ".c". Compilers generally use the name suffix to indicate what programming language a program is in, because Xcode can work with several programming languages, not just with C.

Now click on main.c. Its contents should show up in the editor as text, where different pieces of text are coloured by Xcode to make it easier to tell apart the different parts. Delete the text in this file, and type the following code into the file (don't worry, I'll soon explain what this does):

#include <stdio.h>	// Defines printf etc.

int	main()
{
	// Write a string of text to the shell window:	
	printf( "Masters of the void." );
	
	return 0;	// Tell OS everything is OK.
}

Save the file, then choose Console from the Run menu to show the "Console" window. The console window is essentially a simplified Terminal.app that is built into Xcode. Here you will see any text your command-line program writes out, and you will also be able to type in text that your program can receive (more on that later). Now, choose Build and Run from the Build menu. "Build" means that it will run the compiler over the text file and create a program from that. "Run" obviously means it will actually start the program.

If you're very quick and look at the grey bar at the bottom of any Xcode window after choosing Build and Run, you'll see that it is telling you what files it is compiling.

It will write "Masters of the void." into the Console window. Not much, but an important step towards learning the basics.

Help, it didn't work!

Xcode status line when there's an error

If you are like me, chances are it didn't work right away. If something goes wrong, the grey bar at the bottom of the Xcode window will say "Build Failed (1 error)" or something similar, and you can click the Errors and Warnings group to see details. If that is the case, click the first error message, and it will open an editor in the lower half of the window where the error occurred. Edit the text so it matches the example code above and try to Build and Run again. Repeat this until it works.

There are a few things worth noting that may help you find errors:

  1. C is case sensitive, that is "Main" and "main" are different words to it. So, make sure you type every character exactly the same as it is written above.
  2. When C doesn't understand something, it will valiantly try to just struggle on until it really can't make sense of your code. So, it is important to try to fix errors in order, because many of the later errors will be "misunderstandings" caused by earlier errors. Also, if you can't find the error on one line, look at the lines above it. Sometimes a mistake is farther up, but C was still able to make sense of the code until at a later point.
Note: If one of the error messages in the Errors and Warnings group doesn't really make sense, you may occasionally need to bring up the "Build Results" window ("Build" menu). That window contains a little button with a "lines of text" icon on it, and when you click that you can view the actual error messages in longer form. Click on an error in the error list at the top and it'll select the corresponding longer line below. You can even make Xcode open that window automatically during compilation (see the Preferences). This also makes it more obvious the build actually happened, because a window will pop up and show you a "live" progress and error list as it happens.

Xcode build results window

So, what did I just do?

Let's look at the main.c file from top to bottom so we understand what we just did:

#include	<stdio.h>	// Defines printf etc.

This first line means that you want to tell your compiler it should put the contents of some other file here, just as if you had typed its contents there. You signal this using the #include command. In this case, you include the file named stdio.h, which is part of the ANSI C standard library. You can enclose the name either in "<" and ">" or in quotes. The former means it's a system file (i.e. part of the ANSI C standard library or code provided by Apple), while using quotes tells the compiler it's one of your own files (we'll get to that later).

Note: ANSI stands for the American National Standards Institute. ANSI C is a standard written down by this group, that tries to provide a common set of rules to which the companies who create C compilers can adhere, ensuring that a program you write on one computer can also be compiled on another. At least in theory.

So what's a #include good for? Glad you asked. You see, a computer is very complex, and even to get a single character displayed on the screen already involves lots of programming work. However, much of this work has already been done by the programmer(s) that wrote the operating system you're working with. They wrote dozens and dozens of files, all like our main.c file. These files contain things like printf in the fourth line of our file, which is basically a command that writes text to the screen.

Usually, every programmer who wanted to draw text on the screen would have to do the work to create their own printf. But programmers are a lazy lot, and so they invented #include. Somewhere on your computer, there is a file named stdio.h, which contains all the code needed for printf, and which is essentially the same as the one used by your operating system (if I may say this in such a simplified way). By including this file, you tell the compiler to do the same as if you had copied the contents of that file into your main.c file. You'll quickly develop a deeper understanding of these include files (or header files, as they're sometimes called, hence the ".h" suffix) and libraries when we get to creating an include file of our own. For now it suffices to know that this #include tells the compiler about printf, which is described below.

Note: By the way, "stdio" is short for "standard input/output". C was originally designed at a time when file names could only be 8 characters in length, so you'll find a lot of abbreviations like this.

The two slashes behind the file's name indicate that the compiler should ignore anything on this line following the two slashes. This is called a comment. Use comments often and always to indicate what a line does, even if it is obvious to you now, since it will make it easier for you if you have to get back to your program a year later. Trust me on this one, it may be annoying at first, but I've had to throw away a couple of good programs I'd spent lots of work on because they were simply unreadable. And most people do not have the discipline to go back to a program and add in all the comments after they've finished the code.

Note: I usually end comments with a full stop (".") when they describe the line they're on, while I use a colon (":") at the end of comments that describe the line(s) below them. I hope that helps you read the comments in these samples better.
int	main()
{
...
}

The following lines after our #include define a routine (a named collection of commands), or in C terms a function. The first word, int, tells the compiler about the return value of this function. If you still remember maths class, if you have an equation

y = f(x)

y is the return value. But in C you don't give the return value a name like "y", you only tell the compiler what kind of data type it is (what type it has). In this case, main() returns an int, which is short for "integer" and means a positive or negative natural number (that is, no fractions). The next word is the name of the function, main. Main is a special function, it is the first one called by your computer when it runs (executes) your program. It's the starting point of your program, and when main() has finished, your program is finished.

The "(" and ")" following main indicate that this function receives no parameters (if it received parameters, like our example "f" above takes "x" as a parameter, it would be between the brackets, more on that later). Then follows the "body" of this function, which contains the commands that make up this function and is enclosed in "{" and "}". Think of the function body as something like a "to-do" list. The computer will simply read this list, and do each item on the list, in order.

	printf( "Masters of the void." );
The first of the two items on our list, the printf-line, is what does the actual output. As you may notice, printf() is a function. It does not provide any interesting return value1, but it takes one parameter, the text to write to the screen, which is always enclosed in quotes. Like all commands inside a function, this command is finished with a semicolon. This is necessary since C allows a command to stretch across several lines. That is:
	printf(
	"Masters of the void."
	);

and

	printf
	(
	"Masters of the void." )
	;

are the same to C. It also doesn't care how many spaces you put in there, or how many tabs (though it does care if it's between quotes). So, go crazy and insert spaces wherever you feel you need them to improve readability, as long as the spaces or tabs or line breaks aren't in the middle of a word.

So, to summarize, this line simply moves "Masters of the void." onto your screen. The last line of the function's body,

	return 0;	// Tell OS everything is OK.
specifies the return value of the function and exits from the function. It should always return the number zero from main(). On some operating systems, if you return something else than zero from main() they think an error has occurred and output an error message.

You now know about main(), about include statements, about comments, and have a vague idea of return values. Not much, eh? Stay tuned, the second lesson will introduce you to more.

Previous | Next

1) Well, actually printf does provide a return value, but we don't need it, so we just ignore it. back

Reader Comments: (RSS Feed)
Edward F. Storm writes:
I'd love to work through your tutorial, but I have a lot of trouble reading it. I'm a little up in years, and
the pale pink type on a white background is almost impossible. And it's a struggle to read the insets
which contain program text and Xcode stuff. Does your tutorial text exist in a pdf format or something
similar? Thanks for any help you can offer.
Uli Kusterer replies:
Edward, there must be something wrong with your screen or browser. There is NO PINK AT ALL on any of my web sites, nor will there ever be. Nor is the background white. Do you perhaps have a custom style sheet set up? Or did you print this and one of your color printer cartridges are empty?

The colors here should be white-on-black text, with a pale prussian blue for the links. While I'm aware that white-on-black is not everyone's cup of tea, it just felt right for this site, and I took great care to maintain high contrast.

That said, there is a plan, eventually, to provide a downloadable/printable version, but that may take a while.
William Scott writes:
The white text on black background does give the illusion of being pale pink. There is something about the anti-aliasing of this in Safari that does make it hard to read. I just turned 45, and don't wear glasses, FWIW.

I use terminals and an editor (TextMate) with a black background and white font, but find it renders better when the anti-aliasing is turned off.
Stephen Johnson writes:
If you have trouble with white text on a black background, I suggest turning on the screen inversion shortcut in the Accessibility prefpane. Then you can just hit cmd+opt+shift+8 whenever you want to read this page.
Comment on this article:
Name:
E-Mail: (not shown on site)
Web Site URL: (optional)
Comment: (plain text only)
Please Enter the following word:
Or E-Mail Uli privately.