Programming Linux Games 1st Edition Loki Software - Download the ebook now for the best reading experience
Programming Linux Games 1st Edition Loki Software - Download the ebook now for the best reading experience
com
https://ebookgate.com/product/programming-linux-games-1st-
edition-loki-software/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/linux-system-programming-1st-edition-
robert-love/
ebookgate.com
https://ebookgate.com/product/go-systems-programming-master-linux-and-
unix-system-level-programming-with-go-1st-edition-mihalis-tsoukalos/
ebookgate.com
https://ebookgate.com/product/gnu-linux-application-programming-1st-
edition-m-timm-tim-jones-jones/
ebookgate.com
https://ebookgate.com/product/erlang-programming-a-concurrent-
approach-to-software-development-1st-edition-francesco-cesarini/
ebookgate.com
Programming Erlang Software for a Concurrent World Second
Edition Joe Armstrong
https://ebookgate.com/product/programming-erlang-software-for-a-
concurrent-world-second-edition-joe-armstrong/
ebookgate.com
https://ebookgate.com/product/software-engineering-for-students-a-
programming-approach-4th-edition-douglas-bell/
ebookgate.com
https://ebookgate.com/product/assembly-language-step-by-step-
programming-with-linux-3rd-edition-edition-jeff-duntemann/
ebookgate.com
https://ebookgate.com/product/the-art-of-r-programming-a-tour-of-
statistical-software-design-1st-edition-norman-matloff/
ebookgate.com
Trademarked names are used throughout this book. Rather than including a funny little trademark
symbol with every occurrence of a trademarked name, we are using the names only in an editorial
fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
Distributed to the book trade in the United States by Publishers Group West, 1700 Fourth Street,
Berkeley, California 94710, phone: 800–788–3123 or 510–528–1444, fax: 510–528–3444
Distributed to the book trade in Canada by Jacqueline Gross & Associates, Inc., One Atlantic Avenue,
Suite 105, Toronto, Ontario M6K E7 Canada, phone: 416–531-06737, fax: 416–531–4259
For information on translations or book distributors outside the United States, please contact
No Starch Press, Inc. directly:
The information in this book is distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc.
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 it.
Foreword i
Preface iii
Who This Book Is For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . iv
Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
Networking APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
BSD Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
OpenPlay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
IPX and SPX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
File Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
libpng and libjpeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
libaudiofile and libsndfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Ogg Vorbis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
The SDL MPEG Library, SMPEG . . . . . . . . . . . . . . . . . . . . . . 68
zlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
4 Mastering SDL 69
Computer Graphics Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
The Framebuffer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
The SDL Video API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Setting Up the Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Direct Surface Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Drawing with Blits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Colorkeys and Transparency . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Loading Other Image Formats . . . . . . . . . . . . . . . . . . . . . . . . . 92
Alpha Blending . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Achieving Smooth Animation with SDL . . . . . . . . . . . . . . . . . . . 97
Input and Event Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Processing Mouse Events . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Processing Keyboard Events . . . . . . . . . . . . . . . . . . . . . . . . . . 112
Processing Joystick Events . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Multithreading with SDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
CONTENTS 5
Bibliography 405
Foreword
I was honored when John asked me to write the foreword for this book. I’ve
spent the last few years in an opportunity that few have had, the opportunity to
get up close and personal with the source code to quite a few of the world’s most
popular (and some less popular) games. I’ve had the chance to port these games
to the Linux operating system, something that has been a source of sweat and
sometimes swearing, but always of pride and joy.
In these pages you will find the jewels of wisdom that John has picked up over a
year of picking our brains, experimenting, and experience. Much of the
information contained here has never been documented all in one place, so
whether you’re a beginner looking to start an open source game or a seasoned
professional, I think you’ll find something to interest you. John has done a great
job presenting the tools available for developing your games on Linux.
Enjoy!
Sam Lantinga
Author of SDL
Preface
A few years ago I was browsing the computer section at a local bookstore when I
bumped into another computer enthusiast. He introduced himself as a game
programmer, mentioned a few of the projects he had worked on, and told me
about his latest fascination: Linux. It meant little to me at the time, but I filed
the conversation away for future reference, and eventually I remembered the
name and installed Linux on my home computer.
The first few months were not easy. Linux is vastly different from DOS or
Windows, and it took some getting used to. But persistence paid off, and soon I
felt confident enough with Linux to make the permanent switch. The
development tools rocked, and I was impressed by the fact that code mistakes
almost never led to system crashes. Once I realized what I’d been missing, I
never wanted to go back to Windows again.
Except to play games. A group of friends from school used to hold networked
gaming parties (netfetes, in the parlance of the crowd), and all of the games they
played relied on Windows and DOS. I reluctantly kept a minimal copy of
Windows on one of my drives so I wouldn’t be left out of netfeting.
Linux is a great operating system for developers, and even for casual users who
don’t mind the initial learning curve. But until recently, Linux has been lousy
for gaming. This isn’t due to any technical shortcoming; Linux has plenty of
performance and stability to support high-performance multimedia applications.
It did, however, lack support from game developers. Thanks to portable game
programming toolkits like SDL and OpenAL, this is beginning to change. Linux
still hasn’t seen very much original game development, but Linux users now have
access to ported (converted) versions of a number of major commercial games,
produced mainly by Loki Software, Inc.
iv PREFACE
Game programming has been one of my hobbies ever since my first Commodore
64 computer, and I wasn’t about to leave it behind when I left the Windows
world for Linux. The SVGALib library held me over for a while, but SDL
quickly took over as my favorite way to write Linux games. After meeting the
Loki crew at a Linux trade show, I decided that Linux gaming meant business,
and got the idea to write a book about it. A year later, it is finally finished, and
I hope you enjoy reading it.
Online Resources
I made the decision to not include a CD-ROM with this book. This choice was
both personal and pragmatic. Books CDs tend to get lost or damaged, no
matter how hard one tries to keep them in a safe place. CD inserts are usually
impossible to open without damaging the book in some way. And finally, the
PREFACE v
data that would be contained on the CD (presumably the libraries and examples
we’ll talk about in this book) would be obsolete by the time the book hit the
press.
Instead, we’ve put together a Web site with all the book’s examples and links to
various libraries you’ll need. You can access this site from either
http://www.nostarch.com or http://www.lokigames.com. Feel free to share
the example code with your friends and colleagues, and use it in your projects;
license details are included in the code archive.
Acknowledgements
This book would not have been possible without help from a lot of people.
No Starch Press was a pleasure to work with, even when I switched from SGML
to LATEX in the middle of the project and mentioned that I would need printouts
instead of Word documents for copyedit. I thank everyone at
No Starch—especially Karol Jurado and Bill Pollock—for their patience and
willingness to accomodate a first-time author. Thanks also to Amanda Staab for
making Programming Linux Games known to the world.
I’d like to thank the Loki crew for keeping my life interesting during the summer
of 2000; especially Sam Lantinga for tolerating my never-ending SDL and
framebuffer console questions, Joe Valenzuela for helping me get up to speed on
OpenAL, and Lance Colvin for providing me with a place to stay during the
summer. Scott Draeker was always there to answer questions and provide
feedback, even in the midst of slipping deadlines an an ever-changing table of
contents. This book would not have happened without his ongoing support.
The following people deserve a virtual beer for helping me in various ways. The
list is long, but so was the process of writing this book. Here goes:
Martin Donlon for starting the SDL Documentation Project and providing me
with helpful hints as I wrote Chapter 4, Ray Kelm for for commenting on Win32
portability issues, Matt Friedly of http://phluid.acid.org for allowing me to
use some of his tracker music (reflux.ogg) in Penguin Warrior, my Georgia Tech
roommates Daniel Larsen, Matt Might, Anthony Chen, and Frank Cheng for
tolerating my odd hacking hours and fits of frustration over badly-documented
APIs, Mike Phillips for obtaining excellent screenshots (which unfortunately I
could not use due to the virtual impossibility of dealing with game company
vi PREFACE
John Hall
Atlanta, GA
Chapter 1
Simulation Games
physics system for simulating the physics of the real world, realistic input
response, network capabilities, and possibly a certain amount of artificial
intelligence for the computer-controlled players, a contemporay sim is not trivial
to construct.
What makes a simulation game successful? Let’s look at a couple of examples: a
“realistic” simulator and an “action” simulator. Microsoft Flight Simulator is a
popular flight simulator for the PC (and is in fact the current iteration of a long
line of flight simulators by the same developers, dating back to the Commodore
64) that combines realistic control with excellent 3D graphics and interesting
airplanes, and the terrain looks reasonably close to the real world’s.1 An
experienced pilot could certainly tell the difference between Microsoft Flight
Simulator and a real airplane, but it’s nonetheless an enjoyable simulation.
Microsoft Flight Simulator tries to make the players feel like they were in the
cockpit, not just collecting cellulite behind the keyboard of a fast computer.
Although this game will not run under Linux (except possibly under WINE2 ),
it’s certainly worth a look if you’re thinking of writing a flight simulator.
On another front, the Flight Gear project is presently developing a free flight
simulator for Linux. The simulator already sports a realistic physics model and
an excellent terrain engine, and it is slated to eventually become one of the best
flight simulators ever. Flight Gear is portable to many platforms, as it is based
almost entirely on open technology.
Heavy Gear II from Activision is a good example of an action simulator. It puts
the player behind the controls of a multiton Gear (a two-legged walking vehicle
with big guns) and succeeds because of its realistic graphics, simple but capable
control system, damage simulation, and interesting gameplay. The player is in
complete control of his or her Gear and is free to do anything during the game
1
One of the first rules of game design (and, to some extent, of computer graphics in general)
is that it doesn’t matter if something is realistic as long as it looks realistic. Unfortunately,
most people don’t have 5-terahertz machines, so game creators have to take a few shortcuts.
Most flight simulators really aren’t that realistic when it comes down to it, but they sure
seem realistic.
2
http://www.winehq.com.
4 CHAPTER 1
(although accomplishing the mission without getting killed is usually the best
plan). Heavy Gear II creates a sense of power and euphoria in the player, and
this makes it a pleasant experience. Activision has also published several
MechWarrior titles that are very similar to the Heavy Gear series.
Finally, one of my personal favorite simulation games (from many years ago) is
Corncob 3D, a completely unrealistic shareware, DOS-based flight simulator.
Guised as a flight simulator, this is a classic “Defend Earth from Space Invasion”
game with lots of missions, missiles, and mayhem. By today’s standards, of
course, this game is laughable. But it ran well on the low-end hardware of the
day, and it was a lot of fun to play. Corncob 3D is a good example of a simulator
that trades realism for entertainment value.
First-Person Shooters
First-person shooters are some of the most popular games today. They typically
involve a weak story line (with exceptions, of course), hordes of enemies, big
explosions, and lots of blood. The basic premise of most first-person shooters is
to give the player an adrenaline rush by putting him in the middle of a hostile
THE ANATOMY OF A GAME 5
environment with insidious monsters and powerful weapons. These games have
improved in quality over the years and are beginning to reach a very high level of
realism. Some popular ones are Quake 3, Half-Life, and Soldier of Fortune, all of
which are available for Linux (although Half-Life is not native to Linux, and
requires the WINE library to run).
High-quality first-person shooters are difficult to produce, not just because
they’re hard to program (facilitated by standard 3D libraries such as OpenGL),
but also because they require detailed 3D character models and levels. 3D
game-engine programming requires a solid knowledge of linear algebra and a firm
grasp of certain types of data structures. However, mathematically inclined
people are likely to find 3D game programming both challenging and rewarding.
6 CHAPTER 1
The genre of games known as Real-Time Strategy (RTS ) games includes such
popular titles as StarCraft, Command and Conquer, and Total
Annihilation—games that allow the player to command individual parts of an
army from an overhead view, with success in battle usually leading to better
equipment and soldiers. Because success is usually determined by a player’s
tactics, these are considered strategy games. RTS games often have a high replay
value; they’re fun to play again and again.
RTS games are comparatively easy to program, because, with some exceptions,
they do not involve 3D graphics or complicated mathematics; however, good RTS
games are hard to produce, and they tend to be few and far between. They often
involve a certain amount of artificial intelligence (AI) programming for
controlling the simulated opponents in single-player games—a fascinating field,
but one that we’ll leave to other sources.
THE ANATOMY OF A GAME 7
StarCraft is by far the most successful RTS game, combining pleasing graphics, a
large selection of well-balanced units, and interesting battlefields in a very
well-rounded game and exciting game. Solid game design is by far the most
important issue in creating a real-time strategy game, and StarCraft is an
excellent example. This is not the first notable game from Blizzard
Entertainment, and it will be interesting to see what Blizzard comes up with in
the future.
Turn-Based Strategy (TBS ) games are like real-time strategy games, but the
gameplay is divided into turns, usually with no time limit, thus giving the player
time to think and relax, and lending the game an entirely different feel from the
faster-paced strategy games. TBS games are not decided by reflexes, but rather
by careful planning, which often makes them more difficult, and more attractive
to many players. Sid Meier’s Civilization II is widely regarded as the best
turn-based strategy game, because of its balance and replay value.
Deceptively Complex
I once thought that TBS games were easy to write, but then I saw the
source code to Sid Meier’s Alpha Centauri (SMAC). Most players don’t
realize it, but SMAC actually uses a 3D technique called voxels to
render its units on the fly and to draw a height-sensitive landscape with
perspective texture mapping and dynamic palette mapping (made
possible by self-modifying assembly code). Sid Meier’s Alpha Centauri
was obviously not easy to port to Linux. While it’s possible to write a
good TBS game without such sophistication, don’t think of the TBS
genre as an easy way out—its complexity can be deceiving.
Role-Playing Games
Role-Playing Games (RPGs) stem from the Dungeons and Dragons role-playing
system.3 In this type of game, the player assumes the role of one or more
3
There are lots of similar role-playing systems; I just give DND as an example.
8 CHAPTER 1
characters on some sort of quest. Role-playing games put the player in a world
with many possibilities; a good RPG gives its players a sense of immersion and
true interaction, and allows them to effectively become someone else.
The quality of a role-playing game depends much more on its storyline,
interaction, and depth than on its graphics. Ultima Online is an example of a
good online RPG. While its graphics are not spectacular, the depth of its
gameplay is incredible, because it allows for complex interactions between
players in a virtual universe. Ultima is not exactly a “hard core” RPG, however;
true die-hard RPG gamers often prefer other types of RPGs, such as those
published by Simutronics (http://www.simutronics.com).
THE ANATOMY OF A GAME 9
Puzzle Games
Puzzle games receive less attention than the other game genres, but they deserve
to be mentioned. Puzzle games challenge the player with problems that require
thought and patience. This genre includes everything from simple box-pushing
games (Boxxel and the dangerously addictive Sokoban) to the animated and
ubiquitous Tetris.
A successful puzzle game is usually challenging (but not impossible), pleasant to
look at (graphics should not be ignored), and replayable (one-shot puzzle games
are usually not very enjoyable the second time around, and players don’t
appreciate that). The difficulty involved in creating a puzzle game depends on
the particular game; some are extremely complex, involving massive amounts of
artwork and graphics processing, while others are simple to implement.
10 CHAPTER 1
Multiuser Dungeons
If you’ve never been “mudding,” give it a try. A good MUD can provide a truly
interesting experience. You can find MUDs all over the Internet; just search the
Web for the word “mud.”
The input subsystem receives the user’s commands through an input device (like
the keyboard or a joystick) and records these commands for further processing.
While input device programming is not difficult, it should be done carefully,
because flawed input processing can easily ruin an otherwise excellent game. The
first version of Apogee’s Rise of the Triad (a first-person shooter from several
years ago) suffered from particularly bad input handling, and the game was
aggravating to play until this problem was fixed.
One of the input subsystem’s most important jobs is to simultaneously support a
variety of input devices. A well-written input subsystem should be able to
integrate just about any type of oddball game controller with minimal effort (this
is made a bit easier by libraries like SDL, but it’s still something to keep in mind
as you code). Some players prefer to use joysticks rather than mice, and an input
subsystem should be able to accommodate this preference without modification
to the main game code. As far as the game is concerned, the joystick should
appear as a generic device, capable of producing “left,” “right,” “up,” and
“down” commands. We will discuss SDL’s input handling and abstraction in
Chapter 4, and we’ll touch on the lower levels of input handling in Linux later on.
Nearly every game on the market allows you to remap the keyboard and other
input devices to your liking, and this is a feature that players demand. Many
people have non-US keyboards with different key locations, and you’ll end up
cutting off a lot of would-be players unless you allow them to configure the game
to work with their keyboards. Fortunately, this is not difficult; it can be
accomplished with a simple lookup table. It is also a good idea to allow the
player to store and retrieve multiple key mappings, in case a friend prefers a
different configuration.
The display subsystem conveys the game’s status to the player in a visually
impressive way, whether through simple 2D graphics, or advanced 3D rendering
(the type of graphics you use doesn’t matter, as long as they are appropriate for
the game). Regardless of the type of graphics produced by the display
subsystem, the structure of the code is substantially the same.
THE ANATOMY OF A GAME 13
Although computer audio technology has not been hyped as much as computer
rendering technology during the past few years, a game’s audio subsystem is
every bit as important as its graphics subsystem. Fortunately, producing
high-quality sound on a computer is not as difficult as producing high-quality
graphics.
Sound is easy to play back (usually a simple matter of a few function calls with a
multimedia toolkit), but creating production-quality sound effects for a game is
as much an art as creating graphics, and should be left to a specialist. Stellar
sound effects can boost a game’s atmosphere, and lousy sound effects can
seriously damage a game’s potential.
3D enhanced audio is one of the latest trends in computer sound technology with
modern sound cards (like Creative’s SB Live! series) supporting four-speaker
surround-sound, and 3D-aware sound-processing to simulate the Doppler effect
and other complex sound wave interactions. (Simple two-channel stereo sound
just falls short of the immersive environments of today’s 3D games.) In fact,
some sound cards can even accelerate these effects in hardware. Several
14 CHAPTER 1
competing 3D sound APIs have emerged, and we will discuss one of these
(OpenAL) in Chapter 5.
Games generally have to track a lot of rapidly changing data, including the state
of the player and the condition of each enemy—information that must be
updated frame by frame to keep the game moving. The update subsystem
manages this data.
The update subsystem is the game’s brain. It enforces the game’s rules for
movement upon the player, “plays” the role of each enemy (which might involve
a certain amount of artificial intelligence), ensures that every object is within the
allowed boundaries, and inflicts injuries. It could almost be said that the other
game modules are merely interfaces to the update subsystem.
THE ANATOMY OF A GAME 15
Keyboard
Mouse I nput Subsystem
Game Pad
LAN or
Network Subsystem Internet
Update Subsystem
3D Hardware /
Framebuffer Di spl ay Subsystem
The game (see Figure 1–1) loop is the “glue” that binds the various game
subsystems. It is simply a while loop that runs throughout the entire game,
looping anywhere from 30 to 60 times per second. The game loop invokes the
correct routines to gather input from the player and from the network, updates
16 CHAPTER 1
the status of all objects in the game, draws the next frame of graphics, and
produces audio. While this process may sound complicated, it is actually quite
trivial, because all of this functionality is provided by the game’s input, network,
graphics, and audio subsystems.
The game loop should start as soon as the game’s other subsystems have been
initialized, and should end when the player exits the game. It may be a good
idea to separate the menu system from the main game loop in some cases, but
doing so could actually complicate the game’s code. With a properly written
game loop, a game becomes a “state machine” that acts on its current state
based on the player’s input.
Organization is important too, since the game loop sequences the other
subsystems. This should not be a haphazard decision; for instance, the data
gathered from the networking subsystem often influences the decisions of the
other subsystems, so it should be invoked first. The graphics subsystem should
probably be last, since it reflects the data generated by all of the other
subsystems.
As you can see, a game engine is conceptually simple, but the devil is in the
details. In the next chapter we’ll become familiar with the tools we’ll use for
Linux game programming, and then we’ll start to work with the libraries and
interfaces that make it all possible. If you’re already familiar with development
tools like gcc and gdb, you may wish to skim over Chapter 2 and move on to
Chapter 3 or 4.
Chapter 2
Programming Editors
Before we can dive into the subject of Linux game coding, we’ll need a way to
write our source code. Although simple editors such as pico and joe are sufficient
for some simple tasks, they are inadequate for programming. It would be
preferable to use a text editor with support for syntax highlighting, brace
matching, and other features. Let’s take a look at several of the more popular
code editors. If you have never written code with a UNIX-like system, it would
be a good idea to try out these editors to see which one best suits your
programming style. This chapter is not meant to be a reference manual or
tutorial for these editors; rather, it is starting point for those who have never
written code on a UNIX-like platform.
18 CHAPTER 2
vi
Emacs
GNU Emacs is uncontested as the behemoth of text editors (indeed, some think
of it as an operating system in itself). It is based on its own variant of the Lisp
programming language; almost all of the editor’s functionality is implemented in
customizable Emacs Lisp. Emacs has a loyal following among programmers,
partly because absolutely every aspect of this editor can be changed by the user.
I started writing this book with NEdit, but I eventually switched over to Emacs
because it works well on the Linux console and doesn’t require a mouse. (I’m
also a bit of a Lisp enthusiast, and in that regard Emacs is a perfect match.)
Emacs is not as difficult as vi to learn initially; there is simply a lot more to
learn. Its basic commands and keystrokes are not hard to get used to, but
becoming fluent with Emacs is a major undertaking. Emacs includes a mail and
news client, editing modes for nearly every language you’d ever want to use,
several types of documentation readers, and even optional IRC clients and web
browsers. Many of these features define their own sets of command keys, leaving
much for the would-be user to learn. In return for this hassle, Emacs provides an
enormous amount of power; it’s quite literally possible to set your login shell to
Emacs and never leave its environment.
To get started with Emacs, run the editor (the command is usually emacs), press
Ctrl-h, and then t. The Emacs tutorial will open, and you can use it to learn
the basic keys and editing modes.
In addition to the “real” GNU Emacs, there are several other editors that are
very similar in capabilities and usage. XEmacs1 is a code fork from GNU Emacs
with a number of added features and an improved interface. JED2 is a
programmer’s editor that closely resembles Emacs but has fewer features and a
smaller memory footprint.
1
http://www.xemacs.org
2
http://space.mit.edu/%7Edavis/jed.html
20 CHAPTER 2
NEdit
NEdit, the “Nirvana Editor,” is a very slick code editor from Fermilab.4 It is
neither as absurdly customizable as Emacs nor as ubiquitous as vi, but it is
much easier to learn (since its keystrokes are similar to those of many popular
word processors) and powerful enough for serious work. NEdit’s main downside
is that it requires the X Window System to run. It is a good idea to have at
least a working knowledge of another editor if you choose to use NEdit for your
daily work. This book was written partly with NEdit (though I later switched to
Emacs). Although previous versions of NEdit were encumbered by a license that
was not palatable to most Linux distributors, the NEdit license was changed to
the GNU General Public License with the 5.1 release. The editor is now truly
free software, and it is currently under active development by a team of
volunteers.
3
ftp://ftp.gnu.org
4
http://www.nedit.org
LINUX DEVELOPMENT TOOLS 21
gcc is the most popular C compiler for Linux. It was developed by the Free
Software Foundation for the GNU project, and it is available on many platforms.
gcc is free software, and it is included as a standard component of nearly every
Linux distribution. There are several other C/C++ compilers for Linux (such as
Kai C++ and the as-yet-unreleased Metrowerks CodeWarrior), but gcc is used
for the vast majority of Linux software development. Some eschew gcc (and its
C++ brother, g++) as quirky or incomplete, but in reality it’s at least as good as
the other mainstream C compilers.
gcc’s basic job is to compile C source code into executable programs. To compile
one or more files, simply pass them to gcc on the command line as follows:
If there are no serious errors, gcc will create an executable file named a.out in
the current directory. Otherwise, you will receive warning and error messages
describing the problems the compiler encountered, and gcc will not produce any
compiled output. If you list multiple files on the command line, gcc will compile
them separately and attempt to link them into one executable, stopping if any
22 CHAPTER 2
individual file produces an error. If gcc is given files that end in .o (object files)
or .a (static libraries), it will link them directly into the executable. This allows
gcc to serve as a simple interface to the linker.
Warning
You may be in the habit of using the shell’s tab-completion feature to
fill in filenames. Be careful when you do this with gcc; it’s easy to
accidentally overwrite your source files by accidentally tab-completing
the wrong filenames. This may seem obvious, but I’ve lost work because
of it.
-o filename
Outputs to the given filename instead of the default a.out. For
instance, -o foo will cause the program to be compiled into an
executable named foo (or foo.exe under Windows).
That’s it for gcc! It has a few quirks and obscure features, but we’ll get to those
as we need them.5 Like most GNU tools, gcc comes with excellent online
documentation. In particular, refer to the manpage or info node for a description
of gcc’s command-line options.
5
Richard Stallman’s book Using and Porting gcc is the authoritative guide to hacking gcc.
24 CHAPTER 2
Creating Makefiles
Make looks for targets and rules in a file called Makefile or makefile. This file
can contain any number of targets. If Make is started with no command-line
options, it automatically attempts to rebuild the first target it encounters.
Consider the following makefile:
This file describes how to build an executable called program and a static
library called graphics.a. (Don’t worry about the commands for building the
library—we’ll discuss libraries later in this chapter.) program depends on
file1.c, file2.c, and graphics.a. If any of these have been modified since
program was last built, Make will rebuild program. graphics.a is also a target,
and it depends on graphics.c and draw.c. The indented lines under each target
are rules. If program needs to be rebuilt, Make will execute the two rules that
have been provided. These lines must be indented with tab characters; spaces
will not work. Make is rather particular about syntax.
Variable Substitution
CC=gcc
CFLAGS=-O2 -W -Wall -pedantic
LIBS=-lSDL -lpthread
As you can see, variables are substituted into the makefile with the $(VARNAME)
notation. This is a literal text substitution, and it takes place before the rule is
otherwise processed. What if you want to add to the end of a variable without
destroying its old contents? You might try something like this:
FOO=bar
FOO=$(FOO) baz
FOO=$(FOO) qux
At a glance, it would appear that the FOO variable would end up with the value
bar baz qux. However, Make does not normally evaluate variables until they
are used (in targets), so FOO actually ends up with the string $(FOO) qux. There
are two solutions to this problem. GNU Make (the default Make on Linux
systems) provides a := operator for assignments, which causes its right-hand side
to be evaluated before the variable is assigned. It also provides a += operator for
directly appending to variables. A more portable solution would be to assign
bar, baz, and qux to three different variables and to combine them all at once:
BAR=bar
BAZ=baz
QUX=qux
FOO=$(BAR) $(BAZ) $(QUX)
This (hacked) solution allows the variable FOO to be constructed correctly when
it is used in a rule. It is a rather ugly way to do so, however, so we suggest using
the GNU Make extensions.
Although the use of variables might lengthen a makefile, they can provide a nice
bit of abstraction. Variables make it easy to modify the options used throughout
the build process without changing the whole makefile.
LINUX DEVELOPMENT TOOLS 27
Implied Rules
Since C files are almost always compiled with the cc command (which is a
symbolic link to the gcc command on Linux machines), there is really no need to
specify build rules for each source file in the project. Make allows for implied
build rules. That is, if a target is followed by no rules and does not specify any
dependencies (or it simply does not exist), Make will attempt to use a default
build rule based on the target’s file extension.
For example, let’s say that foo.c is a C source file containing the function bar
and that main.c is a C source file containing a main function that calls bar.
The following makefile will build the program. Notice that there is no target for
foo.o—it is referenced by the foo target, and Make assumes that it should create
the target by compiling the file foo.c. (Actually, Make knows of several different
source file types, C being perhaps the most common.) When Make automatically
invokes the C compiler, it adds the CFLAGS variable to the command line.
Phony Targets
Programmers often use Make for purposes other than building executables. It’s
really a general-purpose project management tool. For instance, I’m currently
using a makefile so that I don’t have to delete a bunch of files and then run
LATEX, MakeIndex, and dvips every time I want a preview of this book. Consider
the following makefile:
foo: foo.c
gcc foo.c -o foo
clean:
rm *.o
rm foo
The clean target has no dependencies and is therefore built only when it is
specifically requested on the command line. The command make clean causes
Discovering Diverse Content Through
Random Scribd Documents
“Don’t you believe a word of that ’ere stuff. It’s all gammon, I tell
you. They can do without us a great deal better nor we can do
without them. They’ve got the whole world to resort to, and can git
their supplies anywhere they please.”
“Yes, I know that; but then they haint got anything other nations
want. It was our cotton what brought all the gold and silver into the
country.”
“There’s that old song again. Why, they’ve got the best perducing
land in the world. And their corn and cattle aint to be sneezed at the
world over.”
“Well, that may all be true,” rejoined the other, “but they can’t
whip us.”
“Well, suppose we whip them, what will be gained?”
“Why, we’ll stop the ’tarnal thieves from stealing our niggers.”
“Now that’s a grand mistake. Don’t you see every nigger in the
South will break right for the North, for there won’t be no Fugitive
Slave Law then. And then you know what a dreadful time we had
not long ago up Lowndes county with the niggers, for this here
country’s got twice as many niggers as whites.”
At this an angry dispute arose between them, one declaring the
other an abominable Yankee, and the other is stoutly denying it.
Oaths were freely bandied, and the loyal Southerner threatened to
call the corporal of the guard, and have the other arrested. The
latter in the mean time continued to protest that he had said nothing
detrimental to Southern interests.
“Well, how did you know,” said the rabid secessionist, “about the
cattle and corn in New York, if you had never lived there?”
“But I have been there, though I never lived in that region.”
“Well, if that’s the case,” responded his antagonist, “you had
better keep mighty quiet about it, or we’ll treat you like we did John
Peterson, that miserable Yankee that we hung last week to a pine
tree.”
Just then the relief-guard came, and the conversation ceased. I
noted down at the time the dialogue as it occurred, gave the
manuscript subsequently to my friend Captain Steadman, who, in
connection with other papers, as the reader will presently learn,
carried it to Washington city, where I received it from him.
From all this, which was spoken in a most angry and boisterous
manner, and while I held my ear to the key-hole of the prison-door, I
learned what excessive antipathy the Southern people, as a mass,
entertain towards persons of Northern birth. As the reader follows
me through this book, other evidences of Southern ignorance,
malice, and inhumanity will arise, all of which I witnessed or
experienced, and all of which are related with no spirit of hatred, but
as an “ower true tale.” I do not relate these facts in the spirit of a
politician, nor for political purposes; for the nativity, education, and
political antecedents of myself and of the entire family from which I
sprung, have developed a warm support of Democratic principles. To
these I yet ardently adhere, though positively and absolutely
repudiating that form thereof which in the slightest degree affiliates
with treason or oppression.
CHAPTER V.
Southern Inhumanity—A Prison Telegraph—Mobile—Conversation with a Fire-Eater
—Negro Sale Stables—A Bad Sign—Mule-Beef—Montgomery—In the Penitentiary
—Felon Soldiers—Hanging for Theft—Visit to a Condemned Prisoner—Who Shall
Answer?
ebookgate.com