【发布时间】:2021-11-27 13:40:25
【问题描述】:
我正在用 C 语言为设备编写固件。该软件允许 PC 通过串行接口 (UART) 与该设备进行通信。固件包含以下多层:
- 通过 UART 发送和接收数据的通信层。
- 块层:此层通过 UART 向设备写入数据来启用/禁用设备上的某些块。
- API 层:这包含对块层中例程的一系列调用。它用于启用或禁用设备上的一组块。
我的问题是错误处理,因为在 C 中没有异常。以下是我实现固件的方式,我正在尝试看看是否有更有效和更紧凑的方式来构建它,同时仍然有效地处理错误。我想避免在每一层检查下层调用的状态。 下面的代码非常紧凑,实际上,我在块层中有很长的 send_uart_commands 序列。
// Communication layer
operation_status_t send_uart_command(command_id_t id, command_value_t value)
{
// Send data over UART
// Return success if the operation is successful; otherwise failure
}
// Block layer
operation_status_t enable_block1(void)
{
if (send_uart_command(BLOCK1_COMMAND_1, 10) != operation_success)
return operation_failure;
if (send_uart_command(BLOCK1_COMMAND_2, 20) != operation_success)
return operation_failure;
// A list of sequences
if (send_uart_command(BLOCK1_COMMAND_N, 15) != operation_success)
return operation_failure;
return operation_success;
}
operation_status_t enable_block2(void)
{
if (send_uart_command(BLOCK2_COMMAND_1, 1) != operation_success)
return operation_failure;
if (send_uart_command(BLOCK2_COMMAND_2, 8) != operation_success)
return operation_failure;
return operation_success;
}
// API layer
operation_status_t initialize(void)
{
if (enable_block1() != operation_success)
return operation_failure;
if (enable_block2() != operation_success)
return operation_failure;
// A list of calls to the functions in the block layer
return operation_success;
}
【问题讨论】:
-
提供的代码到底有什么问题?我很确定任何能够内联 ang squashing goto 的合理编译器都会生成最佳程序集
-
@tstanisl 我的问题是重复的错误处理,我必须为每个函数做。
-
@tstanisl 嗯,我记得那个。到处都有很多不好的建议。我会怀着极大的怀疑态度阅读那里的所有内容。
-
重复不一定是坏事;它可以使代码更容易阅读和调试,而不是试图变得“聪明”。
标签: c exception error-handling firmware