Tải bản đầy đủ (.pdf) (502 trang)

IT training learn c on the mac (2nd ed ) mark bucanek 2012 12 19

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.14 MB, 502 trang )

BOOKS FOR PROFESSIONALS BY PROFESSIONALS®

Companion

eBook
Available

The perfect introduction for those new to programming, this book teaches
you best practices using the latest tools and techniques. You’ll learn how to
do the following:

• Write and compile native C programs
• Tap into the power of mathematical expressions with variables and
operators

• Empower your programs with pointers and parameters
• Control the direction your program takes with flow control
• Design your own custom data structures
• Create your own command line tools
• Save your program’s data and read it back in again
• Handle errors if things happen to go wrong
Considered a classic by an entire generation of Mac programmers, this new
edition of Learn C on the Mac has been updated for the latest C standards,
which are the foundation for all OS X and iOS app development. Turn to
Learn C on the Mac, and find the knowledge and skills that will help you master C programming.

A complete course on C programming for the beginner

Learn C on the Mac

S



tart programming with Learn C on the Mac. You don’t need to know anything
about programming—not one little bit. You’ll start with the basics and,
guided by expert Mac developers, take small steps that will help you learn the
essentials of C, the gateway to programming your Mac, iPhone, or iPad.

SECOND
EDITION

Mark
Bucanek

COMPANION eBOOK
US $39.99

SOURCE CODE ONLINE

www.apress.com

Shelve in
Mobile Computing
User level:
Beginning-Intermediate

Learn C
on the Mac
For OS X and iOS
SECOND EDITION
David Mark | James Bucanek



V413HAV

For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.


Contents at a Glance
 About the Authors ...............................................................................xiii
 About the Technical Reviewer.............................................................xiv
 Acknowledgments................................................................................xv
 Introduction.........................................................................................xvi
 Chapter 1: Go Get the Tools!.................................................................. 1
 Chapter 2: Programming Basics ......................................................... 11
 Chapter 3: C Basics: Statements and Functions ................................. 21
 Chapter 4: C Basics: Variables and Operators .................................... 43
 Chapter 5: Debugging.......................................................................... 75
 Chapter 6: Controlling Your Program’s Flow ...................................... 93
 Chapter 7: Pointers and Parameters................................................. 137
 Chapter 8: More Data Types .............................................................. 177
 Chapter 9: The Command Line .......................................................... 229
 Chapter 10: Designing Your Own Data Structures ............................ 291
 Chapter 11: Working With Files......................................................... 331
 Chapter 12: Handling Errors.............................................................. 381
 Chapter 13: Advanced Topics............................................................ 411
 Chapter 14: Where Do You Go from Here?......................................... 455
 Appendix: Answers to Excercises ..................................................... 467
 Index.................................................................................................. 477
iv



Introduction
Welcome Aboard
Welcome! Chances are that you are reading this because you love the Mac. And not only do you
love the Mac, but you also love the idea of learning how to design and develop your very own Mac
programs.
You’ve definitely come to the right place.
This book assumes that you know how to use your Mac. That’s it. You don’t need to know
anything about programming—not one little bit. We’ll start off with the basics, and each step we
take will be a small one to make sure that you have no problem following along.
This book will focus on the basics of programming. At the same time, you’ll learn the
essentials of the C programming language.
In Douglas Adam’s book The Hitchhiker's Guide to the Galaxy, the answer to “the Ultimate
Question of Life, the Universe, and Everything” is determined to be “42.” That answer is, of
course, wrong; the correct answer is “C.”
The C language is the wellspring of software. The nothing-short-of-miraculous revolution in
computing and consumer electronics over the past half century has largely been accomplished
using C, languages that are direct descendants of C (Objective-C, C++), or languages designed to
work like C (Java, C#). Learn C and the programming world is your oyster.

 Note Douglas Adams was a big Macintosh fan.

Once you get through this book, you’ll be ready to move on to object-oriented programming
and Objective-C—the official programming language of OS X and iOS.
Does this all sound a little overwhelming? Not to worry; in this book, we’ll take small steps, so
nobody gets lost. You can definitely do this!

Who Is This Book For?
When Dave wrote the very first edition of Learn C on the Mac back in 1991, he was writing with

college students in mind. After all, college was where he really learned to program. It seems he
was way off.

xvi


INTRODUCTION

“My first clue that I had underestimated my audience was when I started getting e-mails
from fifth graders who were making their way through the book. Fifth graders! And not just one
but lots of nine-, ten-, and eleven-year-old kids were digging in and learning to program. Cool!
And the best part of all was when these kids started sending me actual shipping products that
they created. You can’t imagine how proud I was and still am.”
Dave was really on to something. Over the years, we’ve heard from soccer moms, hobbyists,
even folks who were using the Mac for the very first time, all of whom made their way through
Learn C on the Mac and came out the other end, proud, strong, and full of knowledge.
So what do you need to know to get started? Although learning C by just reading a book is
possible, you’ll get the most out of this book if you run each example program as you encounter
it. To do this, you’ll need a Mac running OS X (preferably version 10.6.8 or later) and an Internet
connection. You’ll need the Internet connection to download the free tools Apple has graciously
provided for anyone interested in programming the Mac and to download the projects that go
along with this book.
Again, if you know nothing about programming, don’t worry. The first few chapters of this
book will bring you up to speed. If you have some programming experience (or even a lot), you
might want to skim the first few chapters, and then dig right into the C fundamentals that start in
Chapter 3.

The Lay of the Land
Here’s a quick tour of what’s to come in this book.



Chapter 1 shows you how to get the free software tools you’ll use throughout this
book.



Chapter 2 explains some of the basics of how computer programs are built.



Chapter 3 shows you how to embed a series of programming statements into a
reusable function, something you can call again and again.



Chapter 4 adds variables and operators into the mix, bringing the power of
mathematical expressions into your programs.



Chapter 5 teaches you how to watch your program execute, line-by-line, to see that
it’s doing the right thing, or fix it if it’s not.



Chapter 6 introduces the concept of flow control, using constructs like if, else, do, and
while to control the direction your program takes.




Chapter 7 covers pointers and parameters, two concepts that will add a dramatic new
level of power to your programs.



Chapter 8 moves beyond the simple data types used in the first half of the book,
adding the ability to work with more complex numbers along with data types like
arrays and text strings.

xvii


INTRODUCTION



Chapter 9 takes a break to show you how to deploy your finished program and use it
from the command line.



Chapter 10 dives even deeper into data and teaches you how to design your own
custom data structures.



Chapter 11 shows you how to save your program’s data and read it back in again by
introducing the concept of the data file.




Chapter 12 gives you some techniques for dealing with errors, for when things go
wrong.



Chapter 13 covers a variety of advanced topics—typecasting, unions, recursion,
sorting, collections, and much more.



Finally, Chapter 14 wraps things up and points you to the next step on your journey.
Ready to get started? Let’s go!

xviii


Chapter

1

Go Get the Tools!
If you want to build a house, you need a solid set of well-crafted tools. Building
computer programs is no different. Programming requires a specialized set of
development tools-----basically, programs that make programs.
In the early days of C, you only needed a few, relatively simple tools. As
computers have become more sophisticated, so has the universe of
development tools. Today, it’s not uncommon to employ dozens of programs to
create even a ‘‘simple’’ application: editors, compilers, linkers, debuggers,
emulators, profilers, analyzers, and more. Add to that list programs that help you

find documentation, cross reference your code, record your development
history, and, well, it’s starting to look like a whole hardware store full of tools!
The good news is that Apple has come to your rescue. Just as Apple has used
an elegant user interface to demystify their most sophisticated applications,
they’ve done the same for software developers. (That’s you!)

Installing Xcode
Apple’s Xcode is a complete hardware store of software development tools,
packaged and delivered as a single application. All you have to do is write your
program and Xcode will-----behind the scenes-----direct the scores of individual
development tools needed to turn your idea into reality. It would make the
Wizard of Oz proud.
NOTE: An application that organizes multiple development tools into a single
workspace is called an integrated development environment (IDE). Xcode is an IDE.

1


2

CHAPTER 1: Go Get the Tools!

And getting Xcode into your computer couldn’t be easier. The entire Xcode
development suite is available from the App Store.
Launch the App Store, go to the Developer Tools category (or just search for
‘‘Xcode’’), and click to install Xcode, as shown in Figure 1-1. Don’t worry if your
screen looks a bit different than the figure. Apple is constantly updating Xcode,
so there will probably be a new version of Xcode in the App Store by the time
this book hits the shelves (or your screen).


Figure 1-1. Installing Xcode from the App Store

That’s it! Sit back and wait for Xcode to download and install. And you’re going
to have to wait awhile, as it’s a really big application. So amuse yourself with the
rest of this chapter while it downloads. Switch to the Purchases view, at the top
of the App Store window, if you want see how the download is progressing.

How much is that IDE in the Window?
Xcode has gone through various prices in the past. Apple really wants you to
create great applications and has strived, for the most part, to make its
developments tools freely available.
It used to be that Xcode was only available to registered developers. Becoming
a registered developer usually costs money, so Xcode was ‘‘free’’ only in the
sense that the prize inside a cereal box is ‘‘free.’’
For a while, Xcode was priced at $5. As of this writing, Xcode is free in the App
Store. Hopefully, it will stay that way.


CHAPTER 1: Go Get the Tools!

NOTE: If you’re running an older version of OS X and don’t have access to the App
Store, you can still download an earlier version of Xcode—but we don’t recommend
it.
The first problem you’re going to encounter is how to get your copy of Xcode. As of
this writing, you must be a registered developer to obtain an older version of Xcode.
Unfortunately, Apple no longer offers free developer registration—largely because
Xcode is now available for free in the App Store—so you’ll have to pay to register,
and that can be expensive. If you are a registered developer or have access to
Apple’s University Program for higher education, you can log into
and download the tools.

But your biggest problem is going to be the differences between the current Xcode
and older versions. The code examples in this book will still work and make sense,
but the commands, windows, features, and controls are all going to be substantially
different. You’re going to have to figure out a lot on your own.
We certainly don’t want to discourage anyone from learning C on the Mac, but we
strongly recommend you upgrade to the latest version of OS X so you have access to
the latest version of Xcode.

What’s a Registered Developer?
So what’s a registered developer and do you need to be one? The short answer
is ‘‘not yet.’’
Becoming a registered developer grants you access to even more tools and
resources than just Xcode. But you don’t need any of that to write great
applications for OS X or iOS! You don’t need it to use Xcode. You certainly don’t
need to be a registered developer to work through this book (or most other
books, for that matter).
You will need to become a registered developer if you want to sell, or even give
away, your masterpieces on any of Apple’s app stores. How cool would that be?
You can register at any time, so there’s no hurry. When you are ready, visit
/>
3


4

CHAPTER 1: Go Get the Tools!

Getting the Projects
While you’re still waiting for Xcode to download and install, why not get the
project files for this book? Everything you need to create the projects in this

book is described in the text, but downloading the finished projects from the
Apress web site will save you a lot of typing.
Go to Below the book’s
description, you’ll see some folder tabs, one of which is labeled Source
Code/Downloads. Click that tab. Now find the link that downloads the projects for
this book. Click that link and a file named Learn C Projects.zip will download
to your hard drive.
Locate the file Learn C Projects.zip in your Downloads folder (or wherever the
browser saved it). Double-click the file to extract its contents, leaving you with a
folder named Learn C Projects. Move the folder wherever you like.

Using Xcode
Once Xcode has finished installing, launch it as you would any application, from
the dock or LaunchPad. When first launched, Xcode will present its startup
window (Figure 1-2).


CHAPTER 1: Go Get the Tools!

Figure 1-2. Xcode startup window

The startup window has convenient buttons that create a new project, reopen a
recently visited project, link to the Xcode documentation, and some other stuff
we’re not going to cover in this book.
Xcode organizes your work around a project. A project is a collection of files that
ultimately produce a program. It always consists of a project document (the icon
with the little blueprint) stored inside a folder, as shown in Figure 1-3. That folder
is called the project folder. You open a project by opening the project
document.


5


6

CHAPTER 1: Go Get the Tools!

Figure 1-3. The contents of a simple Xcode project folder

When opened in Xcode, your project appears in a workspace window, as shown
in Figure 1-4. The window is full of cryptic settings and seemingly complex
controls, but don’t worry. Until you get to some really advanced programming,
you won’t need to fiddle with any of these settings.

Figure 1-4. A workspace window in Xcode

Creating a New Xcode Project
While Xcode still has that ‘‘new car smell,’’ let’s take it for a quick spin around
the block and create a new Xcode project.
To do this, either click on the link labeled Create a new Xcode project link in the
startup window, or choose File  New  Project from the menubar. You’ll be


CHAPTER 1: Go Get the Tools!

presented with the new project assistant, shown in Figure 1-5, which will help
you specify the type of new project you want to create.

Figure 1-5. New project assistant


The left side of the new project assistant lets you choose whether to create a
project for iOS (one that will run on your iPhone, iPad, or iPod touch) or for Mac
OS X (one that will run on your computer). Select Application in the Mac OS X
section.
Next, you need to decide the type of Mac OS X application you want to build. In
this book, you’re going to learn how to build simple, text-only applications that
display text in a window, one line at a time. Once you finish this book, you can
move on to books that will teach you how to use the skills you’ve just mastered
to build applications that will run on your iOS device or on your Mac with the
graphical elements that define those devices.
Select Command Line Tool from the templates pane. This is the only project
template you’ll be using in this book. To complete your selection, click the Next
button.

7


8

CHAPTER 1: Go Get the Tools!

The next screen (Figure 1-6) lets you name your new project and specify a few
other options. For a command-line tool the options are pretty simple. Enter Hello
in the Name field.
The field Company Identifier allows Xcode to specify who made this application.
Typically, this is a reverse of a domain name you’ve set up for your product.
Unless you’ve got a specific identifier you want to use, use one we’ve set up for
this book. Enter com.apress.learnc in the Company Identifier field.

Figure 1-6. Project template options


Set the Type pop-up menu to C, since you’ll be writing all your programs in the
C programming language.
Automatic Reference Counting doesn’t apply to C. Leave the Use Automatic
Reference Counting checkbox unchecked.
Now that your options are all set, click the Next button.
Finally, Xcode will prompt you for a location in which to save your project folder.
Though you can save your projects anywhere you like, you might want to first


CHAPTER 1: Go Get the Tools!

create a master folder, perhaps named My Learn C Projects, in which you can
store all the projects you create for this book

The Workspace Window
Xcode opens your new project in a workspace window, as shown in Figure 1-7.
The workspace window is divided up into panes or views. On the left are the
navigators (how you get around your project). In the middle are your editors
(where you write and design your application). To edit a file, double-click the file
in the navigator and it will appear in the editor. On the right are utilities
(inspectors, libraries, help, and such). Any of these views can be hidden as you
work. In Figure 1-7, the utilities are hidden for the sake of simplicity.

Figure 1-7. Hello project workspace window

At the bottom you’ll find the debug area, which normally appears only while
you’re running or testing a program. This is where you inspect your program
while it’s running and view its output. At the very top is the toolbar. It has
buttons and controls for things you commonly do. The big Run button at the left

will build and run your program, which is what it’s all about. Everything in the
toolbar is just a shortcut for a command in the Xcode menubar; it doesn’t matter
which you use.

9


10

CHAPTER 1: Go Get the Tools!

Running a Project
One really nice thing about Xcode project templates is that they always create a
finished project. That is, everything it needs to build and run is ready right from
the start. Of course, it won’t do anything useful. In fact, it really won’t do much
of anything at all beyond starting and then stopping again. Changing your
project to do something useful is your job.
But don’t let that stop you; let’s make your new project do nothing! Click the
Run button (the big Play button in the upper left corner of the workspace
window). Xcode will assemble all of the parts of your project (a process know as
building) and will then execute it.
Don’t expect fireworks. The Xcode command-line template makes a project that
causes the words ‘‘Hello, World!’’ to appear in the lower right pane (called the
console), as shown in Figure 1-7.

HELLO, WORLD!
Dennis Ritchie developed the original C language over a period of time between hippies and
disco. Years later, he worked with Brian Kernighan to pen a complete description of the
language. This version of C became known as K&R C.
In their seminal book, the very first example of C (it’s on page 6; you can look it up) was a tiny

program that caused the words “Hello, World” to appear on a console. And in those days it was
probably a Teletype console—a washing-machine–sized mechanical typewriter with roll paper.
Ever since that day, practically every book that explains, teaches, or describes a programming
language starts with an example that makes the words “Hello, World” appear somewhere. In the
spirit of that grand tradition, we are honor bound to teach you how to make “Hello, World!”
appear on your Mac!

Moving On
Believe it or not, you are now ready to learn C on the Mac!
You’ve installed all of the tools you need to create OS X applications, and
you’ve created, built, and run a brand new application. That’s pretty good for
one chapter!
The next chapter will take a break from all of this excitement to talk about the
software development process in general.


Chapter

2

Programming Basics
Before we dig into C programming specifics, let’s spend a few minutes
discussing the basics of programming. Why write a computer program? How do
computer programs work? We’ll answer these questions and look at all of the
elements that come together to create a computer program, such as source
code, a compiler, and the computer itself.
If you are already familiar with the basics of programming, please feel free to
skim through this chapter and, if you feel comfortable with the material, skip on
ahead to Chapter 3. The goal here is to get you familiar with the steps involved
in creating a running a simple program.


Programming
Why write a computer program? There are many reasons. Some programs are
written in direct response to a problem too complex to solve by hand. For
example, you might write a program to calculate a value to 5,000 decimal places
or to determine the precise moment to fire the boosters that will safely land the
Mars Rover.
Other programs are written as performance aids, allowing you to perform a
regular task more efficiently. You might write a program to help you balance
your checkbook, keep track of your baseball card collection, or lay out this
month’s issue of Dinosaur Today.
Whatever their purpose, each of these examples shares a common theme. They
are all examples of the art of programming. Your goal in reading this book is to
learn how to use the C programming language to create programs of your own.
Before we get into C, however, let’s take a minute to look at some other ways to
solve your programming problems.
11


12

CHAPTER 2: Programming Basics

Some Alternatives to C
As mentioned previously, C is one of the most popular programming languages
around. There’s very little you can’t do in C (or in some variant of C), once you
know how. On the other hand, a C program is not necessarily the best solution
to every programming problem.
For example, suppose you are trying to build a database to track your
company’s inventory. Rather than writing a custom C program to solve your

problem, you might be able to use an off-the-shelf package like FileMaker Pro or
perhaps a Unix-based solution like MySQL or PostgreSQL to construct your
database. The programmers who created these packages have already solved
most of the knotty database-management problems you’d face if you tried to
write your program from scratch. The lesson here is this: before you tackle a
programming problem, examine all the alternatives. You might find one that will
save you time and money or one that will prove to be a better solution to your
problem.
Some problems can be solved using the Mac’s built-in scripting language,
AppleScript. Just like C, AppleScript is a programming language. Typically, you
use AppleScript to control other applications. For example, you could create an
AppleScript script that gets your daily calendar from iCal, formats it just the way
you like it using TextEdit, and then prints out the results. Or you could write a
script that launches Safari and opens each of your bookmarked news sites in a
separate window. If you can use existing applications to do what you need,
chances are good you can use AppleScript to get the job done.
Some applications feature their own proprietary scripting language. For
instance, Microsoft Excel lets you write programs that operate on the cells
within a spreadsheet. Some word processing programs let you write scripts that
control just about every word processing feature in existence. Although
proprietary scripting languages can be quite useful, they aren’t much help
outside their intended environments. You won’t find much use for the Excel
scripting language outside Excel, for example.

What About Objective-C, C#, C++, and Java?
There is a constant debate as to which programming language is the best one to
learn first. Naturally, the C++ people think that C++ is by far the best language
to start with. Java, C#, and Objective-C people feel the same way about Java,
C#, and Objective-C. But the truth is that all of those languages are based on C.
And if you learn C first, you’ll have a huge leg up on learning any of them. And



CHAPTER 2: Programming Basics

when the next C-based language hits the streets, you’ll have a leg up on that
one, as well.
In a nutshell, C is the best language to start with because many other languages
use the vast majority of C’s syntax and structure. Objective-C, C++, and Java
each start with C and build on C, each in its own unique way. Learning C first is
like learning to walk before learning how to run. If you learn C first, you’ll have an
excellent foundation on which to base your future programming education.

What’s the Best Programming Language
for the Mac or iOS Devices?
All the programs in this book will run in the console, a simple scrolling text
window that is part of Xcode. If you would like to build applications that feature
the Mac look-and-feel with buttons, scroll bars, and windows, you’ll need to
finish this book, then learn Objective-C and Cocoa (for the Mac) or Cocoa Touch
(for iOS devices).
Objective-C is a programming language based on C. Everything you learn about
C will apply to Objective-C. Objective-C is designed to work with objects.
Objects are blocks of code that represent parts of your program, such as a
scrolling window, an image, or a menu. Cocoa is a vast collection of objects that
represent all the elements of the Mac experience. Objective-C was designed to
work together with Cocoa and Cocoa Touch.
Learn C, Objective-C, and Cocoa, and you will have everything you need to
develop even the most complex Macintosh applications. Learn C, Objective-C,
and Cocoa Touch, and you will have everything you need to develop
applications designed to run on mobile devices running iOS.


Learn C on the Mac is the beginning of a series of books that will teach you how

to build professional Mac and iOS applications. Once you’ve finished this book,
you’ll want to dig into Learn Objective-C on the Mac, 2nd Edition by Mark
Dalrymple, Scott Knaster, and Waqar Malik (Apress 2012). It was designed as a
sequel to Learn C on the Mac and does a great job taking you from C to
Objective-C.

Learn Cocoa on the Mac was written by Jack Nutting, Dave Mark, and Jeff
LaMarche (Apress 2010). It completes the cycle, giving you everything you need
to build your own scrollable, clickable Mac applications.
If you are interested in building applications that run on the iPhone, iPod touch,
or iPad, check out Beginning iOS 6 Development by Dave Mark, Jack Nutting,
and Jeff LaMarche (Apress 2012). Beginning iOS Development was also written

13


14

CHAPTER 2: Programming Basics

as a sequel to Learn Objective-C. Instead of focusing on Cocoa, though, it
focuses on Cocoa Touch.
So, first, finish this book, and then make your way through Learn Objective-C on
the Mac. If Mac application design is your goal, next pick up a copy of Learn
Cocoa on the Mac. If the iPhone, iPod touch, or iPad is your thing, pick up
Beginning iOS Development.
And that’s the road map. Oh, one more thing. You can find each of these books
on the Apress web site at .


The Programming Process
In Chapter 1, you installed the Mac development tools and went through the
process of creating a project, which you then built and ran. Let’s take a look at
the programming process in a bit more detail.

Source Code
No matter their purpose, most computer programs start as source code. Your
source code will consist of a sequence of instructions that tells the computer
what to do. Source code is written in a specific programming language, such as
C. Each programming language has its own set of rules (called syntax) that
defines what is and isn’t legal in that language.
Your mission in reading this book is to learn how to create useful, efficient, and,
best of all, legal C source code.
If you were programming using everyday English, your source code might look
like this:

‘‘Hi, Computer! Do me a favor. Take the numbers from 1 to 10,
add them together, and then tell me the sum.’’
If you want to run this program, you need a programming tool that understood
source code written in English. Sadly, computers don’t understand English (yet).
Instead, you must use a precise language, like C, to explain to the computer
exactly what you want it to do. Listing 2-1 is an example of code that sums
numbers 1 through 10.


CHAPTER 2: Programming Basics

Listing 2-1. Summing Numbers 1 through 10 in C
#include <stdio.h>

int main (int argc, const char * argv[])
{
int number, sum;
sum = 0;
for ( number=1; number<=10; number++ )
sum += number;
printf("The sum of the numbers from 1 to 10 is %d.\n", sum );
return 0;
}

If this program doesn’t mean anything to you, don’t panic. Just keep reading. By
the time you finish this book, this will all make perfect sense.
In case you were wondering, here’s what appeared in the console window when
we ran this program:
The sum of the numbers from 1 to 10 is 55.

Want to try this out for yourself? In Chapter 1, you downloaded the project files
for the book from the Apress web site. Open the Learn C Projects folder on
your hard drive. Next, open the folder named 02.01 - Sample, and double-click
the file named Sample.xcodeproj to open the project in Xcode.
Figure 2-1 shows the workspace window for Sample.xcodeproj. The window is a
complex beast, full of incredibly useful tools to help with your programming
pursuits. The most important part of the project window (at least for the
moment) is the editing pane, the area that allows you to edit your source code.

15


16


CHAPTER 2: Programming Basics

Figure 2-1. The Sample project workspace

Run the program by clicking the Run button in the toolbar, by choosing the
Project  Run command, or by typing ⌘R.
The program should build and then run, and the text we showed you previously
should appear in the console pane. If you don’t see the console pane, choose
the View  Debug Area  Show Debug Area command.
OK, enough reveling. Let’s get back to the programming process.

Compiling Your Source Code
Once your source code is written, your next job is to hand it off to a compiler.
The compiler translates your C source code into instructions-----a sequence of
numeric codes-----that make sense to your computer. These instructions are
known as machine language or object code. Source code is for you; machine
language/object code is for your computer. You write the source code using an
editor, and then the compiler translates your source code into a machinereadable form.


CHAPTER 2: Programming Basics

NOTE: Don’t let the terminology bog you down. Read the rest of this chapter, just to
get a basic sense of the programming process, and then move on to Chapter 3. We’ll
lay out everything step-by-step for you, so you won’t get lost.
Think of the process of building and running your program as a three-stage
process. First, Xcode compiles all your source code into object code. Next, all
the object code in your project is linked together by a program called a linker to
form your application. That finished application (called an executable) is what
actually runs on your computer.

Take a look at Figure 2-2. This project contains two source code files, one
named main.c and another named extras.c, as well as an object file named
libc.dylib. Sometimes, you’ll find yourself making use of some code that
others have already compiled. Perhaps they want to share their code but do not
want to show you their source code. This is the way Apple makes their code
available to programmers. They compile the code and save it a special object
file called a library. Or perhaps you’ve built a library of code that you’d like to
use again and again, but don’t want to recompile each time you use the code.
By adding a library of pre-compiled code to your project, you can save some
time and gain immediate access to a world of solutions.
As it turns out, a library called the C Standard Library comes with Xcode and
every other C development environment in the universe. Hmm, that must be why
they call it ‘‘standard.’’ The C Standard Library comes packed with an incredible
number of useful programming bits and pieces that you can use in your own
programs. (This library is so commonly used you don’t even have to ask Xcode
to include it in your project; it just does so automatically.) We’ll talk about those
bits and pieces as we make use of them throughout the book.

17


18

CHAPTER 2: Programming Basics

Figure 2-2. Project with multiple source files

Building Your Application
Xcode starts by compiling main.c and extras.c source files, shown in Figure 22, turning them into object code. Next, all three object files are linked together
by the linker to create a runnable application. The programs in this book were all

designed to run in the console window. As you make your way through the rest
of the books in this series, you’ll learn how to add the rest of the pieces
necessary to create applications that can be run from the Finder. For now,
Xcode’s console will do just fine.
This entire process-----turning source code into a finished program-----is called a
build. Xcode’s build command takes care of all of the details for you. It
determines what compilers you need, keeps track of the libraries your code links
to, finds a place to store all of the intermediate files created by the compilers
and linkers, and keeps those files organized and up-to-date.
The great thing about Xcode is that you’ll probably never have to concern
yourself with any of these under-the-hood details. You just write your source
code and press the Run button. Xcode will take care of the rest.


CHAPTER 2: Programming Basics

What’s Next?
At this point, don’t worry too much about the details. The basic concept to
remember from this chapter is how your C programs run: they start life as
source code and then get translated into object code by the compiler. Finally, all
the object code gets linked together to form your runnable application.
Now, let’s get to the business of writing your very first C program.

19


×