ec.h
1 #include "/usr/include/stdint.h" //intptr_t的声明 2 3 #define EC_CLEANUP_BGN\ 4 ec_cleanup_bgn:\ 5 { 6 7 #define EC_CLEANUP_END\ 8 } 9 10 11 //注意__FILE__等是两个下划线 12 #define ec_cmp(var, target)\ 13 {\ 14 if((intptr_t)(var) == (intptr_t)(target))\ 15 {\ 16 std::cout << __func__ << "[" << __FILE__ << ":" << __LINE__ << "]\n";\ 17 goto ec_cleanup_bgn;\ 18 }\ 19 } 20 21 #define ec_null(x) ec_cmp(x, NULL) 22 #define ec_neg1(x) ec_cmp(x, -1) 23 #define ec_false(x) ec_cmp(x, false)
main.c
1 #include "ec.h" 2 3 #include <fcntl.h> 4 #include <unistd.h> 5 6 #include <iostream> 7 #include <cstdlib> 8 #include <cstdio> 9 10 using std::cout; 11 using std::endl; 12 13 bool fcn(); 14 15 int main(void) 16 { 17 ec_false(fcn()); 18 19 //exit(EXIT_SUCCESS); 20 cout << "EXIT_SUCCESS\n"; 21 return 0; 22 23 EC_CLEANUP_BGN 24 //exit(EXIT_FAILURE); 25 cout << "EXIT_FAILURE\n"; 26 return -1; 27 EC_CLEANUP_END 28 29 } 30 31 bool fcn() 32 { 33 char* p = NULL; 34 int fdin = -1, fdout = -1; 35 36 ec_null(p = (char*)malloc(1000)); 37 ec_neg1(fdin = open("in", O_RDONLY)); 38 ec_neg1(fdout = open("out", O_WRONLY)); 39 40 return true; 41 42 EC_CLEANUP_BGN 43 free(p); 44 if(fdin != -1) 45 (void)close(fdin); 46 if(fdout != -1) 47 (void)close(fdout); 48 return false; 49 EC_CLEANUP_END 50 51 }
记住这种用宏的方式处理函数调用或者系统调用错误检测的实现,虽然这个例子不完善,有BUG。