Up to this point, whenever you wanted to compile a program you
compiled the file displayed in an Emacs buffer. The Compile This
File... option of Emacs' Compile menu (or equivalently,
M-x compile) is a handy feature when your entire program is contained
with one file. It is, of course, possible to compile a file
completely independently of Emacs.
Inside the UNIX Shell window, connect to the separate1 directory
that is contained with the examples directory of your home
directory. What does it contain?
Click here for the answer
This program prints out ``Hello world'', and you can compile and run
it without ever displaying it in Emacs. To compile it, type the
following into your UNIX Shell window:
gcc -Wall -c hello.c
This command resulted in a new file being created in the ``separate1''
directory to which you are currently connected. Use the ls
command to list the directory. What is the new file?
Click here for the answer
At this point you still don't have an executable program that you can
run. The next step is to link the object file to produce such an
executable. To do this, type the following into your UNIX Shell
window:
gcc -o hello hello.o -lm
Linking hooks up your compiled code with some additional C-specific
code. Once again, a new file has been created in the ``separate1''
directory. List the directory. What new file do you find?
Click here for the answer
Now that you have an executable you can run it in the familiar way.
Simply type ``hello'' into the UNIX Shell window.
To summarize, the steps involved in compiling, linking, and running a
program are:
- Compile the ``.c'' file containing the source code with a command
such as
gcc -Wall -c hello.c
The -c in the command is important--it tells C to produce an
object file called (in this case) ``hello.o''. The -Wall part is
optional but is strongly encouraged--it tells C to produce all possible
warning messages. A warning message will usually lead you to a bug in your
program.
- Link the ``.o'' file to produce an executable with a command such as
gcc -o hello hello.o -lm
The -o hello in the command is important--it tells C what to name
the executable. The -lm part tells C to link in the math libraries. If
your program doesn't use any of the match functions from ``math.h'', you can
leave this part out.
- Run the executable in the usual way.
If your entire program is contained within a single file, you can do the
compilation and linking in one step by entering the command
gcc -Wall -o hello hello.c -lm
This is exactly what Emacs does when it compiles a program for you. We have
been careful in this lesson to do the compilation in two separate steps so that
you will be able to deal with programs made up of more than one file. We will
explore this topic further in the next lesson.
Hamlet Project
hamlet@cs.utah.edu