Skip to content

Instantly share code, notes, and snippets.

@mattiasgustavsson
Last active April 2, 2025 17:02
Show Gist options
  • Save mattiasgustavsson/7d2aa93f52835196bae57f95e194616f to your computer and use it in GitHub Desktop.
Save mattiasgustavsson/7d2aa93f52835196bae57f95e194616f to your computer and use it in GitHub Desktop.
Custom assert macro for windows
//------------------------------------------ assert.h ----------------------------------------------------
#ifdef _MSC_VER
#ifdef NDEBUG
#define ASSERT( expression, message )
#else
int display_assert_message( char const* expression, char const* message, char const* file, int line,
char const* function );
#define ASSERT( expression, message ) \
do { \
if( !( expression ) ) { \
if( display_assert_message( #expression, (message), __FILE__, __LINE__, __FUNCTION__ ) ) { \
__debugbreak(); \
} \
} \
} while( 0 )
#endif
#else
#include <assert.h>
#define ASSERT( expression, message ) assert( expression && message )
#endif
//------------------------------------------ assert.c ----------------------------------------------------
#ifdef _MSC_VER
#include <windows.h>
#include <crtdbg.h>
#include <stdio.h>
int display_assert_message( char const* expression, char const* message, char const* file, int line, char const* function ) {
#define ASSERT_DIVIDER "**********************************************************************"
static char buf[ 1024 ];
_snprintf( buf, 1000, "ASSERTION FAILED!\n\n%s\n\nExpression: %s\n\nFunction: %s\n\n%s(%d)\n",
message, expression, function, file, line );
OutputDebugStringA( "\n" ASSERT_DIVIDER "\n" );
OutputDebugStringA( buf );
OutputDebugStringA( ASSERT_DIVIDER "\n\n" );
printf( "\n" ASSERT_DIVIDER "\n" );
printf( "%s", buf );
printf( ASSERT_DIVIDER "\n\n" );
strcat( buf, "\nBreak into debugger?\n" );
int result = MessageBoxA( 0, buf, "Assert", MB_ICONERROR | MB_YESNOCANCEL | MB_SYSTEMMODAL | MB_SETFOREGROUND );
switch( result ) {
case IDCANCEL: {
// Turn off memory leak reports for faster exit
#ifndef NDEBUG
int flag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); // Get current flag
flag ^= _CRTDBG_LEAK_CHECK_DF; // Turn off leak-checking bit
_CrtSetDbgFlag( flag ); // Set flag to the new value
#endif
_exit( EXIT_FAILURE ); // Exit application immediately, without calling crt's _atexit
} break;
case IDYES: {
return 1; // Break to editor
} break;
case IDNO: {
return 0; // Continue execution
} break;
}
return 0;
#undef ASSERT_DIVIDER
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment