如何让用户在我的库中提供自己的功能?

时间:2021-09-19 22:50:16

I am writing a static library for an AVR MCU. I am using avr-gcc and AVR Libc. Some of the library functions use SPI to communicate with a device. However, SPI communication is not done the same way on all AVR MCUs (not all of them have the same registers concerned). It can even be done by big-banging. Thus, I want the user to provide its own SPI routine, for its specific application.

我正在为AVR MCU编写静态库。我正在使用avr-gcc和AVR Libc。某些库函数使用SPI与设备通信。但是,SPI通信并不是在所有AVR MCU上都以相同的方式完成(并非所有AVR都有相同的寄存器)。它甚至可以通过大爆炸来完成。因此,我希望用户为其特定应用提供自己的SPI例程。

How can I do this? Should all the library functions take a callback function as an additional argument? Should I have a global variable within the library acting as an SPI handler? Should I make the function external (using extern)?

我怎样才能做到这一点?是否所有库函数都将回调函数作为附加参数?我是否应该在库中充当SPI处理程序的全局变量?我应该将功能设为外部(使用extern)吗?

Thank you,

1 个解决方案

#1


4  

The simple and straightforward solution is to just declare an appropriately named extern function. This lets you compile your library without the extern function yet existing. But neither you or your users will be able to link a complete executable without providing an appropriate function.

简单直接的解决方案是只声明一个适当命名的extern函数。这使您可以编译库而不存在extern函数。但是,如果没有提供适当的功能,您或您的用户都无法链接完整的可执行文件。

I've used this approach myself and recommend it. It avoids unnecessary complications, uses nothing that isn't absolutely fundamental to all C programming environments, and importantly obvious errors will be flagged at build time not at run time (you won't get runtime crashes as undefined callback functions are called).

我自己也用过这种方法并推荐它。它避免了不必要的复杂化,不使用任何对所有C编程环境都不是绝对基础的东西,重要的是,明显的错误将在构建时标记,而不是在运行时(由于未定义的回调函数被调用,您将不会遇到运行时崩溃)。

#1


4  

The simple and straightforward solution is to just declare an appropriately named extern function. This lets you compile your library without the extern function yet existing. But neither you or your users will be able to link a complete executable without providing an appropriate function.

简单直接的解决方案是只声明一个适当命名的extern函数。这使您可以编译库而不存在extern函数。但是,如果没有提供适当的功能,您或您的用户都无法链接完整的可执行文件。

I've used this approach myself and recommend it. It avoids unnecessary complications, uses nothing that isn't absolutely fundamental to all C programming environments, and importantly obvious errors will be flagged at build time not at run time (you won't get runtime crashes as undefined callback functions are called).

我自己也用过这种方法并推荐它。它避免了不必要的复杂化,不使用任何对所有C编程环境都不是绝对基础的东西,重要的是,明显的错误将在构建时标记,而不是在运行时(由于未定义的回调函数被调用,您将不会遇到运行时崩溃)。

相关文章