Masters of the Void [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.

Welcome to Xcode window

You can either click the Create a new Xcode Project entry there, or if you've already had Xcode open and this window isn't there, 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, select the Application section in the Mac OS X area of the left list and choose the Command Line Tool template, which will give you a very simple C program. Make sure that the Type-popup in the bottom half of the window is set to "C". Click Choose... and then type in MyFirstProgram as the name for the project, then click Save.

Note: Every couple Xcode releases, a helpful Apple programmer re-arranges the categorization in the "New Project" window. If your "New Project" window doesn't look like the screen shot above, try looking through all sections for a template named something like "Standard Command Line Tool" or "C Tool" or something like that.
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, install additional templates as part of SDKs from Apple (e.g. the iPhone SDK) and some applications come with templates for developing plug-ins that will show up under their own heading in this list.

You 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.

Xcode groups and files list

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 a lot of progress and status junk in plain text, but somewhere it will write "Masters of the void." in bold print 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 choose Build Results from the Build menu to see details. Click the first error message to open an editor in the lower half of the window that shows you 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.

Xcode build results window

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 doesn't really make sense, or seem truncated, you may occasionally need to use the little button with the "lines of text" icon on it at the right end of the "Compile filename" header to view the actual error messages in longer form.

Also, you can make Xcode open the Build Results 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.

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 whole 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 very dramatic, eh? Stay tuned, the second lesson will introduce you to more, and give you a second opportunity to understand all this using a little movie.

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.
marius writes:
HI Uli, hab gerade dein Tut überflogen und was mir besonders auffällt, das sich der weisse Text auf dem schwarzen Background shcwer anschauen lässt. Bei mir verschwimmen die Absätze bei nicht 100%igem Hinsehen zu weissen Blöcken. Die Comments z.B. auf grauem Hintergrund sind schon angenehmer aber irgendwie auch noch nicht das Optimum. Vielleicht gehts nur mir so, ka. wollts nur mal anmerken. Ansonsten ist es aber eine klasse Arbeit und ich finds cool, daß Du Sie den Leuten zur Verfügung stellst! Gruß, marius
Daniel Karlsson writes:
It might be so that the "pink" text is the red texts in the xcode screens. I don't really understand why you have made them so small. Great work with the tutorial Uli.
Uli Kusterer replies:
Daniel, the images are so small for several reasons: 1) because large images use bandwidth, and bandwidth costs me money 2) Because they're supposed to show you the windows and areas, and the text is there as an example, and not really intended to be read.
Richard Henry writes:
Fantastic tutorial. I will definitely be coming back here very often!
Carl Merritt writes:
How can I work through your tutorial using a Windows-based system? Is there an equivalent for Windows of the X-Code used in the Mac? Appreciate your help.
Harlan writes:
I am reading the Tutorial in Safari with no problems. I wonder if its your screen your reading it on? I am on iMac 20" 2008 model. I have the Resolution @ 1680x1050. Theres an option in Safari/Preferences/Advanced Very top UNIVERSAL ACCESS Check the box. And change the number to what ever size you like. You can tell the FONT to be no Smaller then 24 if you like. You can also go in System Preferences/Speech and set up one of the voices and "Speak selected Text when the key is pressed."Set Key" I use that when I dont feel like reading. The Mac just reads it to me! But I can read it just fine. No Pink here.
Harlan writes:
Carl Merritt writes: How can I work through your tutorial using a Windows-based system? Is there an equivalent for Windows of the X-Code used in the Mac? Appreciate your help. Sorry Carl M. XCode is only for Mac. In order to create iPhone Apps you need ANY Intel based Mac. A Mac Mini will do just fine to create Apps for iPhone or a Mac. Xcode will only work in Mac OS X Sorry man. If you watch Apples website in there Referb. section or Clearance you can pick up a Mac Mini for about $380. sometimes. Or you can get an iMac 20" 2.4Ghz around $800. maybe less just depends on the time. Just as long as its Intel you can create apps for iPhone
Ryan Stonebraker writes:
AWESOME!!! it worked!!! now i know how to type on the screen!!! THANK YOU!!
Emily writes:
The natural numbers do not include zero. A better definition would be both positive and negative whole numbers. Otherwise, this is very well written!
Uli Kusterer replies:
Emily, thanks, fixed.
Demian Velasco writes:
This is amazing, thanks a lot
Uli Kusterer replies:
Harlan, I'm sure there are many equivalents for Windows to Xcode, but all the documentation and the descriptions on this site will be for Mac OS X, so you'll have a hard time following along. That said, there is of course Visual Studio on Windows, but AFAIK it has a rather hefty price tag. You could probably install the GCC compiler in a Windows version as well, but then you'll have to do all your compiling on the command line. However this will only let you create Windows programs, of course. You can't do iPhone or Mac applications that way, for that you'll still need a Mac at this point in time.
thinkdunson writes:
there's a free version of visual studio 2008 called express. you can download them (three versions, visual basic, visual C#, and visual C++) from www.microsoft.com/express i would assume that the C++ version also works with C, but it's microsoft, so there's no telling.
Bruno Gatjens writes:
Thank you so much for that tutorials.
Rodolfo Pena writes:
Hi, I really liked this tutorial since I'm trying to learn some C and I'm a mac user, so this is pretty much what I've been looking for. JUst one question, do you recomend any C or C++ manuals for a beginner, I mean, I use to program 18 years ago and the las time I wrote code was 15 years ago, and I use to write on all dead languages like cobol, clipper, dbase, and yeah GWBasic, so, I don't think that will be very useful for me now on the mac, but anyways, I can't remember very well either. Some advice? Thank You!!
Uli Kusterer replies:
Rodolfo, if you're looking for reference documentation, I generally just use the"Open man page..." command in Xcode if I want to remind myself what a particular command does, otherwise I use Google to find out what call to use. For Mac specifics, there is also Apple's http://developer.apple.com web site, though that doesn't really cover much C, as it assumes you already know that part.
Alex Demitri writes:
I love your tutorial! Keep it going, please! Alex =)
Charles Marshall writes:
So, let me see if I'm understanding this correctly: "stdio.h" is a program. "printf" is a command found within the "stdio.h" program. And the "printf" function is, in this example, located within another function, "main". And "return 0" is just a way to let the system know when "main" is finished. Am I close?
Uli Kusterer replies:
Charles, close. "printf" itself is located in "stdio.h", but you are *calling* it from inside another function, "main". Calling a function means telling the compiler to do whatever is inside a function. The "main" here is not a call, you are actually telling the compiler what commands to do when someone calls main. Usually, the operating system calls main, which is why you don't see any call to main here. Also, the brackets { and } tell the compiler when "main" is finished. What "return 0" does is provide a return value, that is it tells the operating system *how* the program finished. If there is an error somewhere, you would return some error-number to give the system a clue what happened. But yes, you're close.
Charles Marshall writes:
Thanks Uli! That clears up a lot for me. Is "main" just a name for this particular function, shown in this example? Or would all programming, in other C examples for instance, also need a "main" function as well?
Uli Kusterer replies:
Charles, "main" is a special name, whatever function you call "main" gets called by the operating system when your progrm runs.
Garotas* writes:
In Xcode 3.1.4 (and maybe earlier) you have to go to the section "Command Line Utility" where you can find the "Standard Tool" which is in fact exactly the same thing like the "Command Line Tool" used for this tutorial. It has a different icon though. I'm just posting it because I couldn't find it right away. And because I think this tutorial is so great that I will be commenting every single page of it! ;)
Chris Patton writes:
Thanks for this tutorial it is very helpful and informative. I ran across this site because I started a blog detailing my journey towards becoming an iphone/mac developer at http://beginneriphonedeveloper.blogspot.com/. I figured that this site would be a helpful link to anybody who is like me and is new to learning about the programming for the mac and iphone. Thanks a million!!!
Lauren writes:
So confused! I've followed this tutorial to the letter but when I Build and Run nothing happens...no error message, no text on the screen, no nothing. The build results say "Build Succeeded" with "no issues". Please help!
Uli Kusterer replies:
Very likely you overlooked the part where it says "choose 'Console' from the 'Run' menu". That window is where any text will be shown. Was that it?
Lauren writes:
Thanks for responding, Uli! I chose the Console from the Run menu and did the Build and Run there. This is the text that popped up: "[Session started at 2010-02-21 13:58:21 -0500.] GNU gdb 6.3.50-20050815 (Apple version gdb-1346) (Fri Sep 18 20:40:51 UTC 2009) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "x86_64-apple-darwin".tty /dev/ttys000 Loading program into debugger… Program loaded. run [Switching to process 267] Running… Programming is fun. Debugger stopped. Program exited with status value:0." Is this all that should've happened?
Uli Kusterer replies:
Assuming that you wrote "programming is fun" instead of "Masters of the Void", then yes. :-)
Comment on this article:
Name:
E-Mail: (not shown, hashed for Gravatar)
Web Site URL: (optional)
Comment: (plain text only)
Please Enter the following word:
Or E-Mail Uli privately.