13.1.3. Basic gcc Usage
By now, you must be itching to know how to invoke all these wonderful
features. It is important, especially to novice Unix and C programmers,
to know how to use gcc effectively.
Using a command-line compiler such as gcc is quite different from,
say, using a development system such as Borland C under MS-DOS.
Even though the language syntax itself is similar, the methods used to
compile and link programs are not at all the same.
Let's return to our innocent-looking "Hello, World!" example.
How would you go about compiling and linking this program?
The first step, of course, is to enter the source code. This is
accomplished with a text editor, such as Emacs or vi.
The would-be programmer should enter the source code and save it
in a file named something like hello.c. (As with most C compilers,
gcc is picky about the filename extension; that is, how it
can distinguish C source from assembly source from object files, and
so on. The .c extension should be used for standard C source.)
To compile and link the program to the executable hello, the
programmer would use the command:
papaya$ gcc -o hello hello.c
and (barring any errors), in one fell swoop, gcc
compiles the
source into an object file, links against the appropriate libraries, and
spits out the executable hello, ready to run. In fact, the wary
programmer might want to test it:
papaya$ ./hello
Hello, World!
papaya$
As friendly as can be expected.
Obviously, quite a few things took place behind the scenes when
executing this single gcc command. First of all, gcc
had to compile your source file, hello.c, into an object file,
hello.o. Next, it had to link hello.o against the
standard libraries and produce an executable.
By default, gcc assumes that not only do you want to compile the
source files you specify but also that you want them linked
together (with each other and with the standard libraries) to
produce an executable.
First, gcc compiles any source files into object files.
Next, it automatically invokes the linker to glue all
the object files and libraries into an executable.
(That's right, the linker is a separate program,
called ld, not part of gcc itself--although it can be said
that gcc and ld are close friends.) gcc also knows
about the "standard" libraries used by most programs and tells
ld to link against them. You can, of course, override these defaults
in various ways.
You can pass multiple filenames in one gcc command, but on
large projects you'll find it more natural to compile a few files at a
time and keep the .o object files around.
If you want only to compile a source file into an object file and
forego the linking process, use the -c switch with gcc, as
in:
papaya$ gcc -c hello.c
This produces the object file hello.o and nothing else.