1 /*my_assert.h*/ 2 #undef my_assert 3 #ifdef NDEBUG 4 #define my_assert(test) ((void)0) 5 #else 6 void my_fassert(char *); 7 /*__LINE__是一個十進制數字常,需轉換爲字符串字面量*/ 8 #define STR(x) VAL(x) 9 #define VAL(x) #x 10 #define my_assert(test) ((test) ? (void) 0 \ 11 : my_fassert(__FILE__":"STR(__LINE__)" " #test)) 12 #endif
1 /*my_assert.c*/ 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 #include "my_assert.h" 6 7 void my_fassert(char *mesg) 8 { 9 fputs(mesg, stderr); 10 fputs(" -- assertion failed\n", stderr); 11 abort(); 12 }
/*my_t_assert.c*/ #define NDEBUG #include <signal.h> #include <stdio.h> #include <stdlib.h> #include "my_assert.h" static int val = 0; static void field_abort(int sig) { if(val==1){ puts("fsuccess testing 'my_assert.h'"); exit(EXIT_SUCCESS); }else{ puts("ffailure testing 'my_assert.h'"); exit(EXIT_FAILURE); } } static void dummy() { int i = 0; my_assert(i==0); my_assert(i==1); } /* * 在每次包含<assert.h>時,assert宏的行爲由是否認義NDEBUG決定, * so此頭文件不具有冪等性 */ #undef NDEBUG #include "my_assert.h" int main(void) { my_assert(signal(SIGABRT, &field_abort) != SIG_ERR); dummy(); my_assert(val==0); ++val; fputs("sample assertion failure message --\n", stderr); my_assert(val==0); puts("failure testing 'my_assert.h'"); return (EXIT_FAILURE); }