有没有人有对C的设计和错误跟踪/控制系统的良好指导? [英] Does anyone have a good guide to designing and error tracking/control system for C?

查看:91
本文介绍了有没有人有对C的设计和错误跟踪/控制系统的良好指导?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C开发的软件工程方面的新人;有没有人有关于如何为C项目(特别是嵌入式)设计错误跟踪或错误控制系统的良好指南?关于C库的错误跟踪的一些说法也是有帮助的。

解决方案

根据我的经验,这里的策略属于几个阵营。




  • 使用全局变量ala errno 。这是如何工作的,基本上任何函数都可以在全局变量中存储一个错误代码,所以执行该函数后,可以读取错误代码,看是否正确执行。在多线程环境中工作时,有一些明显的问题。虽然出现 POSIX.1c指定了该问题的解决方案。


  • 让每个函数都返回一个错误代码。例如:

      RESULT_CODE my_function(int param1,int param2); 

    RESULT_CODE error_code = my_function(10,2);




这种方法的问题是你输了您可以直接从函数返回值的功能。




  • 每个函数都有一个额外的参数来存储结果代码。例如:

      void my_function(int param1,int param2,RESULT_CODE * err); 

    RESULT_CODE error_code;
    my_function(10,2,& error_code);
    switch(error_code)
    {
    case RESULT_OK:
    // all OK
    break;
    case RESULT_NO_MEM:
    //内存不足
    break;
    // etc ...
    }




我已经看到这种方法在商业RTOS中成功使用,并且个人喜欢它,因为我发现它是最不严格的。唯一的潜在缺点是,您必须显式声明一个变量来存储错误代码,即使您不关心结果。在某种意义上,我实际上是这样的要求,因为它迫使你不断地考虑如何处理错误。


I'm new to the software engineering side of C development; does anyone have a good guide on how to design an error tracking or error control system for a C project (especially embedded)? Something talking about error tracking for C libraries would be helpful too.

解决方案

In my experience the strategies here fall into a few camps.

  • Use of global variables ala errno. How this works is essentially any function can store an error code in the global variable, so after executing the function you can read the error code to see if it executed properly. There are some obvious issues here when working in a multithreaded environment. Although it appears that POSIX.1c specifies a solution to that problem.

  • Have every function return an error code. For example:

    RESULT_CODE my_function(int param1, int param2);
    
    RESULT_CODE error_code = my_function(10, 2);
    

The problem with this approach is that you lose your ability to return values from the function directly.

  • Every function has an extra parameter that stores the result code. For example:

    void my_function(int param1, int param2, RESULT_CODE *err);
    
    RESULT_CODE error_code;
    my_function(10, 2, &error_code);
    switch (error_code)
    {
        case RESULT_OK:
            // all OK
            break;
        case RESULT_NO_MEM:
            // out of memory
            break;
        // etc...
    }
    

I've seen this approach used successfully in commercial RTOS, and personally prefer it since I find it the least restrictive. The only potential disadvantage is that you have to explicitly declare a variable to store the error code, even if you don't care about the result. In some sense I actually kind of like that requirement, though, since it forces you to be constantly thinking about how errors are going to be handled.

这篇关于有没有人有对C的设计和错误跟踪/控制系统的良好指导?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆