7.2. Using the printf()-debug method

The printf()-debug method is easy to understand and is still the most common method used to debug applications. To use the method, define the following macro in your codes:

#if !defined(DEBUG)
#define DBGMSG(MSGSTR) ((void)0)
#else
#define DBGMSG(MSGSTR) {
        fprintf(stderr,"In %s() at line %d in file %s: %s"
                , __FUNCTION__, __LINE__, __FILE__, (MSGSTR));
        }
#endif

then call this macro where you would like to print messages, for example:

int main(int argc, char *argv[])
{
    DBGMSG("Hi there!
");
    exit(0);
}

If you compile the source code with the -DDEBUG compiler option,then it will print a debug message very similar to the following line:

In main() at line 16 in file printf-debug.c: Hi there!

Although it is a very commonly used method in the early development cycle, it has the following disadvantages:

  • You may need to recompile your source code every time you want to insert new printf()-debug lines.

  • Debugging multi-threaded applications with the printf()-debug method is not trivial.

  • Because it may cause many calls to printf(), the application performance get degraded in most cases.

  • If you insert the DBGMSG macro too many times, it can be hard to trace the huge quantity of debug messages.

Function-like macros introduced by C99 are very useful when defining the debug macro (see “Function-like macros with variable arguments” on page 9).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset