Compiling and Debugging Tips for C


COMPILING

Compile your code with warnings turned on (-Wall turns on all warnings). And don't ignore warnings as you compile your code; warnings usually indicate a lurking problem that can lead to real problems later. Also, always create a Makefile and use make to build your project code

DEBUGGING

gdb

C programs compiled with the GNU compiler and the -g option can be debugged using GNU's debugger gdb (actually, you can use gdb on code that is not compiled with -g, but unless you like trying to figure out how assembly code sequences map to your source code I wouldn't recommend doing so). This link: gdb, contains some basic "how to use gdb" information that I give my cs21 students. If you have never used gdb, you may want to take a look at it.

purify

Purify is a tool for finding memory access errors in your code (memory leaks, reading uninitialized memory, accessing unallocated memory, array out-of-bounds errors, ...). To use purify:
  1. Set your RSU_LICENSE_MAP environment variable:
    setenv RSU_LICENSE_MAP /usr/local/depot/Rational/config/PurifyPlus_License_Map
    
  2. Link your program with purify. Make sure to specify /opt/rw/purify_cache as the global purify cache (where purify'ed versions of libraries will be cached). Here is an example of part of a Makefile for building a purified version of the merger program:
        CFLAGS = -g
        PURIFY=purify -cache-dir=/opt/rw/purify_cache
    
        ### a bunch of skipped stuff 
    
        pure: $(OBJS) 
            $(PURIFY) $(CC) $(CFLAGS) -o merger $(OBJS) $(LIBS)
    
    To build a purified version of my program, I just type: make pure

  3. Run your program. The purify window will appear. It will display your program's memory access errors as your program runs.

  4. chmod to 644 or 600 the following files that purify creates in your home directory as world-writable:
        .purify.Xdefaults  
        .users.purela   
    

For purify to work correctly it needs to re-write every object and library that you link into your program (purified versions of these libraries will be stored in the global purify cache directory, and purified versions of your .o files will be stored in your private working directory).

For more information, see the purify man page or the Purify User's Guide (there is also a hard copy of this in the Sun lab).