摆脱嵌入式软件中的硬件宏 [英] Get rid of hardware macros in embedded software

查看:50
本文介绍了摆脱嵌入式软件中的硬件宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C 开发嵌入式程序.

I was working on an embedded program using C.

有大量的硬件宏,例如

#ifdef HardwareA 
do A 
#endif

它不可读,并且很难用单元测试覆盖所有不同的路径.

It's not readable, and hard to cover all the different paths with unit tests.

因此,我决定将硬件相关代码移动到 arch 文件夹,并使用 makefile 中的宏来决定链接哪个 arch 文件夹.就像在 Linux 内核代码中一样.

So, I decided to move the hardware related code to arch folders, and using macros in the makefile to decide which arch folder is linked. Like in the Linux kernel code.

但是当我看到 Linux 内核时,我注意到 arch 文件夹中有很多重复项.

But when I saw the Linux kernel, I noticed there are so many duplicates in the arch folders.

当在一个硬件中发现错误但可能影响所有其他硬件时,他们如何对所有相关硬件进行更改?

How do they make the changes to all related hardware when a bug was found in one hardware, but might affect all others?

我认为这样做会不可避免地将重复项带入代码库.

I think doing this way will inevitably bring duplicates into the code base.

有人遇到过这种问题吗?

Does anyone have experience with this type of problem?

如何对包含大量硬件宏的代码进行单元测试?

How to unit test on code which has lots of hardware macros?

重构代码以将硬件宏从源代码中移出?

Refactoring the code to move hardware macros off source code?

推荐答案

听起来您正在替换这样的函数:

It sounds like you are replacing a function like this:

somefunc()
{
    /* generic code ... */

    #ifdef HardwareA 
    do A 
    #endif

    /* more generic code ... */
}

有多个实现,每个 arch 文件夹中一个,如下所示:

with multiple implementations, one in each arch folder, like this:

somefunc()
{
    /* generic code ... */

    /* more generic code ... */
}

somefunc()
{
    /* generic code ... */

    do A 

    /* more generic code ... */
}

通用代码的重复是您所担心的.不要那样做:相反,有一个这样的函数实现:

The duplication of the generic code is what you're worried about. Don't do that: instead, have one implementation of the function like this:

somefunc()
{
    /* generic code ... */

    do_A();

    /* more generic code ... */
}

..然后在 arch 文件夹中实现 do_A():在硬件 A 上,它具有该硬件的代码,而在其他硬件上,它是一个空函数.

..and then implement do_A() in the arch folders: on Hardware A it has the code for that hardware, and on the other hardware, it is an empty function.

不要害怕空函数——如果你让它们成为在 arch 头文件中定义的 inline 函数,它们将被完全优化.

Don't be afraid of empty functions - if you make them inline functions defined in the arch header file, they'll be completely optimised out.

这篇关于摆脱嵌入式软件中的硬件宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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