The cc and c++ commands
are used to compile C and C++ programs
respectively under Linux/FreeBSD.
The options for both are similar, so
I will only cover the cc command,
but simple replacement with c++
Using a text editor, such as vi
or emacs, create the source
files for your program. Assume
main.c, list.c, and
output.c comprise the source
files for our program. The -c
option specifies separate compilation.
Each source file is (separately)
compiled with the following commands:
cc -c main.c
cc -c list.c
cc -c output.c
These commands create the object files
main.o, list.o, and
output.o respectively. The
three object files can be linked together
by including them as command line
arguments to cc.
The output program is specified
using the -o.
To create the executable
prog1 from the three
object files, use the following command:
cc main.o list.o output.o -o prog1
Generally, you will want debugging
information included in your object files
and executable. The -g
option is used to direct the compiler
to include debugging information.
To compile main.c
with debugging information,
use the following command:
cc -g -c main.c
You can also direct the compiler to
optimize the code by using the
-O option. No example is
In some cases, you may be using an
external library for some functions. A
common example is the C math library.
Contrary to popular belief, it is
insufficient to simply #include
<math.h> to use the C math
library. The math.h header
file ONLY declares the functions. You
still need access to the object code.
The -l option directs the
compiler to link in an external library.
The math library code is typically
stored in /usr/lib/libm.a or
/usr/lib/libm.so. To use the
math library, we strip the lib
and extension from the library name. The
command for incorporating the math
cc -o prog1 main.o list.o output.o -lm