A Brief Introduction to Programming In Unix


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++ will work.

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 given.

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 library is

cc -o prog1 main.o list.o output.o -lm

The traditional debugger used in Linux/FreeBSD is gdb. My most frequent use of gdb is to find out where my program core dumps. Assuming you have used the -g option to your compiler to include debugging information, you can debug your program with the command

gdb prog1

You should receive a gdb> prompt. To execute your program in the debugger, use the run command:

gdb> run <command line options for prog1>

Repeat the sequence of interactions that caused your program to crash. When it crashes, gdb should stop and present the prompt again. To show the line where the program crashed use the where command:

gdb> where

gdb has an extensive online help system accessible with the help command.

There is an alternative debugger, ddd that is quite a bit more sophisticated and may be more comfortable if you've been using the Visual C++ debugger. You may have to install the Linux RPM or FreeBSD package for ddd if it is not already installed. Links for ddd usage are given below.


Last modified: Mon Jan 08 14:47:47 Eastern Standard Time 2001