Simple "printf" debugging

Simple printf debugging amounts to inserting fprintf commands that output more or less carefully chosen status information at key points in the program flow, observing that information and deducing what's wrong based on that information.

Although often looked down on by users of modern debugging software, printf debugging continues to prove itself indispensable.

Here are some guidelines for you to start learning the art of debugging:

  1. Build and debug your project one small step at a time.

  2. Switch on all warnings e.g. CFLAGS = -Wall -Werror.

  3. Read carefully the error/warning messages from the compiler and act upon them. If a message seems cryptic, try the clang compiler (install it with sudo apt-get install clang). Clang largely takes the same options as GCC.

  4. Insert fprintf(stderr,...) command at the strategic points of the program and localize the source of the error.

  5. It is of advantage to define a TRACE macro (read the C preprocessor chapter) and use it instead of directly using fprintf function. The macro can then be simply disabled after debugging. For example:

    #ifndef NDEBUG
    #define TRACE fprintf
    #else
    #define TRACE(...)
    #endif
    
    or, more elegantly,
    #ifndef NDEBUG
    #define TRACE(args...) fprintf(stderr,args)
    #else
    #define TRACE(...)
    #endif