This article describes some preprocessor macros for use with debugging C++ code. This system has been extended to use my non-standard I/O system described in a later article.
In addition to the standard C/C++ assert macro I have designed a macro called ASSERT which behaves identically to assert except that it is never turned off (even when the symbol NDEBUG is set). Here is the definition of the macro ASSERT:
#define ASSERT(test) \ do { \ if (!(test)) { \ PRINTF_AND_EXIT((PLEASE_EMAIL_DAVIN \ "*** Assertion failed at (%s:%d) \n\n" \ "*** TEST: %s\n", \ __FILE__, \ __LINE__, \ #test)); \ } \ } while (0) |
As can be seen in the above macro definition, this macro makes use of the following two helper macros. Here is the first:
#ifdef NDEBUG #define PLEASE_EMAIL_DAVIN "Please email davin dot pearson at gmail dot com with the following information:\n\n" #else /* !NDEBUG */ #define PLEASE_EMAIL_DAVIN "\n\n" #endif /* NDEBUG */ |
and here is the second:
#ifdef NDEBUG #define PRINTF_AND_EXIT(ARGS_LIST) \ do { set_gfx_mode(GFX_TEXT,0,0,0,0); allegro_message ARGS_LIST; exit(EXIT_FAILURE); } while (0) #else /* !NDEBUG */ #define PRINTF_AND_EXIT(ARGS_LIST) \ do { printf ARGS_LIST; BREAKPOINT; exit(EXIT_FAILURE); } while (0) #endif /* NDEBUG */ |
As can be seen in the above macro definition, I use and link with the Allegro graphics library, which includes such functions as set_gfx_mode and allegro_message.
I have defined a macro called ASSERT_INFO. Here is the definition of the macro:
#define ASSERT_INFO(test,info) \ do { \ if (!(test)) { \ PRINTF_AND_EXIT((PLEASE_EMAIL_DAVIN \ "*** Assertion failed at (%s:%d)\n\n" \ "*** INFO: %s\n", \ __FILE__, \ __LINE__, \ string(info).const_char_star())); \ } \ } while (0) |
The advantage of this macro over assert and ASSERT is that there is room for debugging information when the assertion fails. The definition of assert_info is straightforward:
#ifdef NDEBUG #define assert_info(test,info) ASSERT_INFO(test,info) #else #define assert_info(test,info) #endif /* NDEBUG */ |
The following macro is equivalent to the statement ASSERT(false):
#define SHOULD_NEVER_HAPPEN() ASSERT_INFO(false, "This line should not be executed"); |
The following macro is equivalent to the statement ASSERT(false), except that (like ASSERT_INFO) it allows for debugging information to be printed when the assertion fails.
#define ERROR(info) ASSERT_INFO(false, info) |
The assert_info macro is roughly equivalent to Java Version 1.5's assertion facility.
Back to Research Projects |
This page has the following hit count:
|