COMPANION eBOOK SEE LAST PAGE FOR DETAILS ON $10 eBOOK VERSIONUS $39.99 Shelve in Macintosh Programming User level: Beginner–Intermediate www.apress.com SOURCE CODE ONLINE • Learn to pr
Trang 1COMPANION eBOOK SEE LAST PAGE FOR DETAILS ON $10 eBOOK VERSION
US $39.99
Shelve in Macintosh Programming
User level:
Beginner–Intermediate
www.apress.com
SOURCE CODE ONLINE
• Learn to program in the C language entirely on your Mac.
• Perfect for beginners—no previous programming experience
is required!
• This new version of the classic C primer from SpiderWorks has been updated to bring you the latest C standards and best practices.
This book is a primer to programming in general and to the C
program-ming language specifically You will not only learn how to program in C in any environment but also take your first steps toward learning how to program for the Mac as well as the iPhone Learn C on the Mac offers a full course in programming, covering such concepts as functions, variables, operators, data types, file management, typecasting, unions, recursion, linked lists, binary trees, and more.
I wrote this book because I love teaching people how to program and because I wish this book had existed when I was first learning C Learn C on the Mac is a perfect starting point for any Mac owner who wants to learn programming with the full power of C.
Dave Mark is a longtime Mac developer and author of more than a dozen titles including Beginning iPhone Development, The Macintosh Programming Primer series, and Ultimate Mac Programming.
Fou rth Edition of the
Cla ssic C P rog ram min g
Primer for the M ac!
Trang 3Learn C
on the Mac
DAVE MARK
Trang 4All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic
or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-1809-8
ISBN-13 (electronic): 978-1-4302-1810-4
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with
no intention of infringement of the trademark.
Lead Editor: Clay Andres
Technical Reviewer: Kevin O’Malley
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Tony Campbell, Gary Cornell, Jonathan Gennick, Michelle Lowman, Matthew Moodie, Jeffrey Pepper, Frank Pohlmann, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Project Manager: Beth Christmas
Copy Editor: Heather Lang
Associate Production Director: Kari Brooks-Copony
Production Editor: Laura Esterman
Compositor/Artist/Interior Designer: Diana Van Winkle
Proofreader: Liz Welch
Indexer: Toma Mulligan
Cover Designer: Kurt Krames
Manufacturing Director: Tom Debolski
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor,
New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springer-sbm.com , or visit http://www.springeronline.com
For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA
94705 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com , or visit http://www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use
eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales
The information in this book is distributed on an “as is” basis, without warranty Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work
The source code for this book is available to readers at http://www.apress.com
Trang 7Contents at a Glance
About the Author xv
About the Technical Reviewer xvii
Acknowledgments xix
Preface xxi
CHAPTER 1 Welcome Aboard 1
CHAPTER 2 Go Get the Tools! 5
CHAPTER 3 Programming Basics 17
CHAPTER 4 C Basics: Functions 25
CHAPTER 5 C Basics: Variables and Operators 49
CHAPTER 6 Controlling Your Program’s Flow 85
CHAPTER 7 Pointers and Parameters 121
CHAPTER 8 Variable Data Types 161
CHAPTER 9 Designing Your Own Data Structures 207
CHAPTER 10 Working with Files 249
CHAPTER 11 Advanced Topics 283
CHAPTER 12 Where Do You Go from Here? 317
APPENDIX Answers to Exercises 323
INDEX 336
Trang 9Contents
About the Author xv
About the Technical Reviewer xvii
Acknowledgments xix
Preface xxi
CHAPTER 1 Welcome Aboard 1
Who Is This Book For? 1
The Lay of the Land 2
CHAPTER 2 Go Get the Tools! 5
Create an ADC Account 5
Download the Tools 6
Installing the Tools 8
Take Your Tools for a Test Drive 10
The Xcode Welcome Screen 11
Creating Your First Xcode Project 11
Saving Your New Project .13
Running the Project 14
Your First Program 14
Downloading the Book Projects 16
Let’s Move On 16
CHAPTER 3 Programming Basics 17
Programming 17
Some Alternatives to C 18
What About Objective- C, C++, and Java? .18
What’s the Best Language for Programming the Mac or iPhone? 20
The Programming Process .20
Source Code 21
Compiling Your Source Code 22
What’s Next? 24
Trang 10CHAPTER 4 C Basics: Functions 25
C Functions 25
The Function Definition 26
Syntax Errors and Algorithms 27
Calling a Function 29
A Brief History of C 32
The Standard Library 33
Exploring Unix and Your Mac’s Built- In Manual 34
Same Program, Two Functions 36
The hello2 Project 37
The hello2 Source Code 40
Running hello2 42
Let’s Do That Again, Again, Again 43
Generating Some Errors 44
C Is Case Sensitive 47
What’s Next? 47
CHAPTER 5 C Basics: Variables and Operators 49
An Introduction to Variables 50
Working with Variables 51
Variable Names 51
The Size of a Type 52
Bytes and Bits 53
Going from 1 Byte to 2 Bytes 55
Operators 56
The +, -, ++, and Operators 57
The += and -= Operators 58
The *, /, *=, and /= Operators 59
Using Parentheses 60
Operator Precedence 61
Sample Programs 63
Opening operator.xcodeproj 63
Stepping Through the operator Source Code 64
Opening postfix.xcode 67
Stepping Through the postfix Source Code 68
Backslash Combinations 70
Support for Backslash Combinations 71
Running slasher 72
Stepping Through the slasher Source Code 73
Trang 11Building slasher the Unix Way 74
Which Compiler Did You Run? 76
Running the Unix Version of slasher 77
Sprucing Up Your Code 77
Source Code Spacing 78
Comment Your Code 80
The Curly Brace Controversy 81
What’s Next? 82
CHAPTER 6 Controlling Your Program’s Flow 85
Flow Control 85
The if Statement 86
Expressions 88
True Expressions 88
Comparative Operators 89
Logical Operators 90
truthTester.xcodeproj 94
Compound Expressions 94
Statements 95
The Curly Braces 96
Where to Place the Semicolon 98
The Loneliest Statement 98
The while Statement 98
The for Statement 101
loopTester.xcodeproj 104
The do Statement 107
The switch Statement 107
Breaks in Other Loops 111
isOdd.xcodeproj 111
Stepping Through the isOdd Source Code 112
nextPrime.xcodeproj 114
Stepping Through the nextPrime Source Code 115
What’s Next? 118
CHAPTER 7 Pointers and Parameters 121
What Is a Pointer? 121
Why Use Pointers? 122
Checking Out of the Library 124
Trang 12Pointer Basics 124
Variable Addresses 125
The & Operator 126
Declaring a Pointer Variable 126
Function Parameters 131
What Are Function Parameters? 132
Variable Scope 132
How Function Parameters Work 133
Parameters Are Temporary 135
The Difference Between Arguments and Parameters 136
What Does All This Have to Do with Pointers? 137
Global Variables and Function Returns 140
Global Variables 140
Adding Globals to Your Programs 141
Function Returns 142
printf() Returns a Value 145
Danger! Avoid Uninitialized Return Values! 145
To Return or Not to Return? 146
More Sample Programs 146
listPrimes.xcode 147
power.xcodeproj 149
Using the Debugger 153
What’s Next? 157
CHAPTER 8 Variable Data Types 161
Data Types Beyond int 161
floatSizer 162
Walking Through the floatSizer Source Code 163
The Integer Types 168
Type Value Ranges 169
Memory Efficiency vs Safety 170
Working with Characters 172
The ASCII Character Set 172
ascii.xcodeproj 173
Stepping Through the acsii Source Code 177
Arrays 178
Why Use Arrays? 179
dice.xcode 180
Stepping Through the dice Source Code 181
Danger, Will Robinson! 184
Trang 13Text Strings 185
A Text String in Memory 185
nameBad.xcodeproj 186
Stepping Through the nameBad Source Code 187
The Input Buffer 188
On with the Program 190
The Problem with nameBad 191
The nameGood Source Code 193
The #define Directive 194
Function-Like #define Macros 196
wordCount.xcodeproj 198
Stepping Through the wordCount Source Code 199
What’s Next? 203
CHAPTER 9 Designing Your Own Data Structures 207
Bundling Your Data 207
Model A: Three Arrays 208
multiArray.xcodeproj 210
Stepping Through the multiArray Source Code 211
Getting Rid of the Extra Carriage Return 217
Adding Error Handling 217
Walking Through the multiArrayWithErrCode Source Code 218
Finishing Up With Model A 220
Model B: The Data Structure Approach 222
structSize.xcode 223
Stepping Through the structSize Source Code 223
Passing a struct As a Parameter 226
Passing a Copy of the struct 228
paramAddress.xcodeproj 229
struct Arrays 230
Allocating Your Own Memory 231
Using malloc() 232
free() 234
Keeping Track of That Address! 234
Working with Linked Lists 235
Why Use Linked Lists? 236
Creating a Linked List 236
dvdTracker.xcodeproj 237
Stepping Through the dvdTracker Source Code 239
What’s Next? 247
Trang 14CHAPTER 10 Working with Files 249
What Is a File? 250
Working with Files: File Basics 250
Understanding File Names 250
Opening and Closing a File 251
Reading a File 253
printFile.xcodeproj 255
Stepping Through the printFile Source Code 256
stdin, stdout, and stderr 258
Working with Files: Writing Files 259
Writing to a File 259
dvdFiler.xcodeproj 259
Creating a New Source Code File 260
Exploring dvdData 261
Running dvdFiler 262
Stepping Through the dvdFiler Source Code 264
Working with Files: Fancier File Manipulation 272
The Update Modes 272
Random File Access 273
Using Random Access Functions 274
dinoEdit.xcodeproj 274
Stepping Through the dinoEdit Source Code 275
What’s Next? 281
CHAPTER 11 Advanced Topics 283
Typecasting 283
Cast with Care 284
Casting with Pointers 285
Unions 287
Why Use Unions? 288
Function Recursion 290
A Recursive Approach 291
Binary Trees 294
Searching Binary Trees 297
Recursion and Binary Trees 298
Function Pointers 301
Initializers 302
An Initializion Example 304
The Remaining Operators 305
Trang 15Creating Your Own Types 308
Enumerated Types 309
Static Variables 310
More on Strings 312
strncpy() 312
strncat() 313
strncmp() 313
strlen() 313
More Standard Library Information 314
What’s Next? 314
CHAPTER 12 Where Do You Go from Here? 317
The Mac User Interface 318
Objective-C and Cocoa 318
Learning Cocoa 319
One Last Bit of Code 320
Go Get ’Em 322
APPENDIX Answers to Exercises 323
Chapter 4 324
Chapter 5 327
Chapter 6 328
Chapter 7 329
Chapter 8 330
Chapter 9 332
Chapter 10 333
Chapter 11 334
INDEX 337
Trang 17About the Author
Dave Mark has been writing about the Mac for the past 20 years His
books include the Macintosh Programming Primer series (Addison-Wesley 1992), Beginning iPhone Development (Apress 2009), and the bestselling previous editions of this book Dave loves the water and spends as much time as possible on it, in it, or near it He lives with his wife and three children in Virginia
Trang 19About the
Technical Reviewer
Kevin O’Malley is a software engineer and author whose articles have appeared on the
Apple Developer Connection, O’Reilly MacDevCenter, and Dr Dobb’s Journal web sites, as
well as in The Perl Journal and IEEE Internet Computing He is the author of Programming Mac
OS X: A Guide for UNIX Developers (Manning Publications 2003) He worked at the University
of Michigan’s Artificial Intelligence laboratory for ten years as a software engineer Kevin was also an adjunct lecturer in the University of Michigan’s Department of Electrical Engineering
and Computer Science, where he taught two programming courses He currently works at
Google in Mountain View, California
Trang 21Acknowledgments
This book could not have been written without the support of my wonderful family Deneen,
Daniel, Kelley, and Ryan, thank you all for everything you’ve done for me I truly am a lucky man
Many, many thanks to the fine folks at Apress My friend Clay Andres started this ball rolling
by bringing me over to Apress Dominic Shakeshaft listened to my complaints with a
gra-cious smile and great British charm Beth Christmas, my esteemed project manager, pushed
when I needed pushing and kept me going when I was flagging My production editor, Laura Esterman, magically managed me across multiple books and kept me from getting things
hopelessly tangled To Heather Lang, copy editor extraordinaire, I am very lucky to have you
as an editor To Grace Wong and the production team, thank you with all my heart; it’s a great pleasure to work with you Thanks to Kari-Brooks Copony, who pulled together this gor-
geous interior design, and to Diana Van Winkle for all the hard work of pouring a confused
set of Word files into this very finished product Pete Aylward assembled the marketing
mes-sage and got it out to the world To all the folks at Apress, thank you, thank you, thank you!
A very special shout out goes to Kevin O’Malley, my incredibly talented tech reviewer Kevin
made many important technical contributions to this book, helping me scrub the prose and
the sample code to ensure that it followed the C standard to the letter Any divergence from
the standard is on me Kevin, I owe you big time, buddy!
Finally, thanks to my friends and colleagues Jeff LaMarche, Dave Wooldridge, Todd Hitt, and
David Sobsey for your patience as I’ve taken time away from our projects to finish this book
I’ll say it again—I am indeed a very lucky man
Trang 23Preface
One of the best decisions I ever made was back in 1979 when I hooked up with my buddy
Tom Swartz and learned C At first, C was just a meaningless scribble of curly brackets,
semi-colons, and parentheses Fortunately for me, Tom was a C guru, and with him looking over
my shoulder, I learned C quickly
Now it’s your turn
This time, I’ll be looking over your shoulder as you learn C My goal is to present every aspect
of C the way I would have liked it explained to me I’ve saved up all the questions I had as I
learned the language and tried to answer them here
Learning to program in C will open a wide range of opportunities for you C is a tremendously
popular programming language and is the basis for Java, C++, and Objective-C Whether you
want to start your own software company or just write programs for your own enjoyment, you will discover that C programming is its own reward Most of all, C programming is fun
I hope you enjoy this book If you have any suggestions or corrections, I’d love to hear from
you In the meantime, turn the page, and let’s get started!
Trang 25w
Chapter 1
Welcome Aboard
elcome! Chances are, 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 C, one of the most widely used programming languages in the world And
once you know C, you’ll have a leg up on learning programming languages
like Objective- C, C++, and Java—all of which are based on C If you are going
to write code these days, odds are good you’ll be writing it in one of these
languages
Once you get through Learn C on the Mac, you’ll be ready to move on to
object- oriented programming and Objective- C, the official programming
language of Mac OS X 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 I wrote the very first edition of Learn C on the Macintosh back in 1991,
I was writing with college students in mind After all, in college was where I
really learned to program It seems I was way off 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
Trang 26not 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
Over the years, I’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 Macintosh 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 Mac OS X (preferably version 10.5 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 down-load the programs 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 2 takes you to Apple’s web site, so you can download the free tools we’ll use throughout this book
! Chapter 3 starts you off with the basics of building a simple program
! Chapter 4 shows you how to embed a series of programming statements into a reusable function, something you can call again and again
! Chapter 5 adds variables and operators into the mix, bringing the power of ematical expressions into your programs
math-! 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 extends the simple data types used in the first half of the book, adding the ability to work with more complex data types like arrays and text strings
Trang 27! Chapter 9 takes this concept one step further, adding the ability to design your own
custom data structures
! Chapter 10 shows you how to save your program’s data and read it back in again by
introducing the concept of the data file
! Chapter 11 covers a variety of advanced topics—typecasting, unions, recursion,
binary trees, and much more
! Finally, Chapter 12 wraps things up and points you to the next step on your journey
Ready to get started? Let’s go!
Trang 29b
Chapter 2
Go Get the Tools!
efore we dig into the specifics of programming, you’ll need to download
a special set of tools from Apple’s web site The good news is that these tools
are absolutely free And, more importantly, Apple’s tools give you everything
you’ll need to create world- class Mac programs, whether they be written in C,
Objective- C, Java, or even C++
To gain access to these tools, go to Apple’s web site and sign up as a member
of the Apple Developer Connection (ADC) program The ADC web site offers
an incredible wealth of information designed to help programmers build
applications for the Mac and for the iPod Touch and iPhone
Here’s the web address to the front page of the ADC site:
http://developer.apple.com
You’ll want to bookmark this page in your browser so you can refer to it later
In fact, you might want to create a Learn C on the Mac bookmark folder in your
browser just for web sites I mention in this book
Don’t let the sheer volume of information on this site overwhelm you Over
time, that information will start to make a lot more sense For now, let’s get in,
get the tools, and get out—no need to linger just yet
Create an ADC Account
Before Apple will let you download the tools, you’ll first need to join ADC’s
iPhone Developer Program or Mac Developer Program Both are free to join
Since not everyone has an iPhone just yet, let’s stick with the Mac Developer
Program
Trang 30On the front page of the ADC web site, click the button that says Visit Mac Dev Center or type this URL into your browser:
Figure 2-1 Click the sign- up link on the Mac Dev Center front page.
Once you complete the sign- up process, make a note of your Apple ID and password These will come in incredibly useful You’ll use them to log in each time you come back to the Mac Dev Center You’ll also be able to use your Apple ID in other areas of the Apple web site, including Apple’s online store
Download the Tools
Once you have your Apple ID, go back to the Mac Dev Center front page (http://
developer.apple.com/mac/)
If you are not already logged in, click the Log in button shown in Figure 2-1 Enter your Apple ID and password, and you’ll be logged in and brought back to the Mac Dev Center front page But this time, you’ll have access to a variety of Mac Dev Center resources Most importantly, you’ll now be able to download Xcode, Apple’s suite of programming tools.Take a look at Figure 2-2: notice the cursor pointing to the Xcode link At the time of this writing, version 3.1 was the latest and greatest version of Xcode Don’t worry if the version number is greater than 3.1 The project files that go along with this book will be updated to run with the latest version of Xcode
Trang 31Figure 2-2 Once you’re logged in to the Mac Dev Center site, find the link to the Xcode download page.
Before you click the Xcode download link, make sure you have plenty of space available on
your hard drive The download file takes up more than a gigabyte (GB) of hard drive space
And you’ll need space to unpack the file and still more space for your programming projects
I would make sure you have at least 3GB of extra space on your drive
CAUTION
It is always a good policy to leave 10 percent of your hard drive empty That gives Mac OS X room to do its
behind-the- scenes maneuvering, with plenty of room to spare If that 3GB you are saving for Xcode will
eat into your 10 percent empty space, consider moving some files off to another drive.
Once you’ve ensured that you have enough hard drive space, click the Xcode link A few
seconds later, your browser will start downloading the Xcode dmg file A dmg file is a disk
image, sort of like a virtual hard drive You’ll see how to open your dmg file in a moment
Trang 32It’s a good idea to check the status of your download, to make sure the download has actually started and to get a sense of how long it will take Your web browser should have
a download window In Safari, you open the download window by selecting Downloads from the Window menu or by pressing !" L My download-in- progress is shown in
Figure 2-3 Note the magnifying glass icon on the right side of the Downloads window Click this icon once your download is complete to open a Finder window containing your dmg file Click the icon, and let’s install the tools
Figure 2-3 Safari’s download window showing the
Xcode download Note the magnifying glass icon on
the right; it will reveal the dmg file in the Finder.
Installing the Tools
Once your dmg file download is complete, double- click the file in the Finder The Finder will open the dmg file (see Figure 2-4) and mount the file on your desktop, just as if it were
a hard drive
Figure 2-4 The Finder is opening and mounting our dmg file.
Trang 33As you can see in Figure 2-5, the dmg file will be mounted as a volume named Xcode Tools
Click Xcode Tools, and double- click the icon labeled XcodeTools.mpkg XcodeTools.mpkg is the actual installer
Figure 2-5 The dmg file mounted as the volume named Xcode Tools
Once the installer launches, follow the instructions In general, when given a choice, use the
default settings In other words, don’t make any changes; just click the continue button You
won’t be able to install Xcode on any drive other than your boot drive Keep going until the
installer tells you the tools are installed This will take a few minutes
NOTE
Once the installer is finished installing the tools, eject the Xcode Tools volume, just as you would any other
volume One way is to click the eject button to the right of the Xcode Tools entry in the Finder Once the
volume is ejected, it will disappear from the Finder Once you are certain that the tools were installed
properly, you might also want to delete the dmg file from your downloads folder, just to save some hard
drive space.
Trang 34Take Your Tools for a Test Drive
Now that you’ve installed the tools, let’s explore The first thing to note is the new Developer folder at the top level of your hard drive Go ahead and take a look It is at the same level
as your Applications folder As you make your way down your programming path, you will spend a lot of time in the Developer folder
Get the idea?
The tools package you just installed came with its own set of applications They live inside their own Applications folder within the Developer folder Unix folks refer to this folder as /Developer/Applications We’ll use this Unix path naming convention throughout this book, because it works really well
TIP
To get to the /Developer folder using the Finder, click the icon for your main drive Unless you renamed it,
it will have the name Macintosh HD
In the Finder, navigate into /Developer/Applications Inside that folder, you’ll find several subfolders along with a number of applications The most important of these applications is the one named Xcode
As you’ll learn throughout this book, Xcode is a program that helps you organize and build your
own programs Technically, Xcode is known as an integrated development environment (IDE)
An IDE is a comprehensive, all-in- one, Swiss Army knife for programmers IDEs typically feature
a sophisticated source code editor (for writing your programs) and a variety of tools for building, running, testing, and analyzing your programs As IDEs go, Xcode is quite a good one
If you are new to programming, don’t let this detail overwhelm you As you make your way through this book, you’ll learn how to use Xcode to create, build, and run a ton of programs
Trang 35All this will be old hat to you very soon For the moment, our goal is to run Xcode, create a test
program, and run the test program, just to verify that we have installed Xcode properly
Double-click the Xcode icon
The Xcode Welcome Screen
When you launch Xcode for the very first time, a welcome screen appears, similar to the one
shown in Figure 2-6 The welcome screen acts as a front end for lots of useful information
that Apple provides Click around, and check out what’s there Don’t worry; you won’t hurt
anything, and it’s good to get a sense of the range of materials available
Figure 2-6 Xcode’s welcome screen
As you get used to working with Xcode, you might get tired of seeing this welcome screen
No problem! To get rid of the welcome screen, uncheck the Show at launch check box in the
lower-left corner of the window
Creating Your First Xcode Project
Xcode organizes all the files you use to build a specific program using something called
a project file The project file is an organization center for all the information related to your project The project file does not hold the resources that make up your project Instead,
Trang 36it knows where everything lives on your hard drive and makes it easy to edit your project elements and combine all the pieces into a running program Again, don’t worry about the details For now, just follow along, and by the end of this book, you’ll feel very comfortable using Xcode.
Let’s create a new project, just to make sure Xcode is installed properly
Select New Project… from the File menu Xcode will bring up a new window asking you to
select the project type that you want to create As you can see in Figure 2-7, there are a lot of different project types The left side of the window lets you choose between iPhone OS and Mac OS X In this book, we’ll be creating projects designed to run on the Mac, so we’ll focus
on the Mac OS X project types
NOTE
In case you’re new to programming, OS stands for operating system Your operating system is the
program running on your computer, iPhone, or iPod that manages all the device’s activities.
Figure 2-7 Xcode prompting you to determine what type of new project you want to create
Trang 37The programs in this book will all make use of the command line utility template Basically,
a command line utility is a program that runs in a text window, without taking advantage
of Mac gadgets like windows, buttons, scroll bars, and the like Though all those graphical
gadgets are fun to work with, and you will eventually want to add them to your programs,
the basics of programming are best explained without adding all that complexity
Click the text that says Command Line Utility in the left- hand pane of the New Project window Then, in the upper-right pane, click the Standard Tool icon Now click the Choose… button
Saving Your New Project
The next step is to decide where to save our new project file When you clicked the Choose… button, Xcode prompted you to select the name of your new project and to select the folder
in which to save your new project Start by navigating over to your Documents folder Now
click the New Folder button, and name your new folder Learn C Projects Navigate into the
Learn C Projects folder, and type hello in the Save As field (see Figure 2-8).
Figure 2-8 Where should you save your new project? Click the Choose… button to select
a destination, and name your new project hello.
Now click the Save button This creates a new folder named hello, creates a new project file,
and saves the project file and its related resources within this folder
Trang 38Running the Project
The most noticeable thing that happened when you clicked the Save button is the ance of the new project window (see Figure 2-9) Your project window is jam- packed with all sorts of buttons, controls, and text Don’t worry about all that stuff Over time, you’ll become quite comfortable with everything you see For now, you only need to know that this project window is your first sign that Xcode is installed properly
Figure 2-9 Your new project window
Your First Program
We have just created a new Xcode project Like all the programs in this book, this project is completely text based—there are no buttons, scroll bars, icons, and so on All the action will happen in a simple scrolling text window known as the console window Before we take our program for a test run, let’s open the console window
Select Console from Xcode’s Run menu A blank console window will appear (see
Figure 2-10)
Trang 39Figure 2-10 The blank console window, before we run our program
As you can see, the body of the console window is blank Let’s run our program and see what happens
Select Build and Run from the Build menu If the console window disappears, bring it to the front by again selecting Console from Xcode’s Run menu.
Our text program puts a time stamp in the console window, telling us exactly when our
program started running It next displays the text Hello, World! followed by an exit status
message, and then exits gracefully (see Figure 2-11) We didn’t have to do anything to the
project to tell the program what to do When Xcode creates a new C project, this program
is what comes right out of the box
Figure 2-11 The console window, showing the text produced when we ran our program
Trang 40Downloading the Book Projects
We need to do one last thing in this chapter before we can move on: download all the sample projects that go along with this book You’ll find them all on the Apress web site This URL will take you to the main web page for Learn C on the Mac:
http://www.apress.com/book/view/9781430218098
In the column on the left side of this web page, you’ll see a section called Book Details and, below that, a section called Book Extras In the Book Extras section, you’ll find a link labeled Source Code Click that link A file called Learn C Projects.zip will download to your hard drive.Locate the file Learn C Projects.zip in your downloads folder and double- click it The file will unzip itself and leave you with a new folder named Learn C Projects That, my friend, contains the keys to the kingdom, the collected projects from the entire book Drag the folder someplace safe If you like, once you’ve placed Learn C Projects in its new home, you can drag it from its new location to the sidebar in a Finder window to make it a bit easier to get to
Let’s Move On
Well, that’s about it for this chapter You’ve accomplished a lot You’ve joined ADC, logged in, downloaded the Xcode installer, installed Xcode, created a new project, and built and run your very first program Awesome! I’d say that calls for a nice, cool beverage of your choice and a well-deserved round of applause
Feel free to quit Xcode if you like We’ll fire it up again in the next chapter See you there!