用宏处理函数调用或系统调用错误检测

本文介绍了一种使用宏定义进行函数调用及系统调用错误检测的方法,并通过具体代码示例展示了如何利用宏来简化错误处理流程。这种方法适用于C/C++等语言,在实际应用中能够有效地提高代码的健壮性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。

转载于:https://www.cnblogs.com/jiayith/p/4075933.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值