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.
How can I do thi开发者_运维知识库s? 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
)?
Thank you,
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.
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).
精彩评论