0
votes

I am going to build a simple library (.a file) in IAR Workbench for STM8. In this library, I want to implement both hardware SPI and software SPI for users to choose.

In my library.c, I wrote:

#include "library.h"

void LibraryInit()
{
#ifdef HARDWARE_SPI
   funcToInitHardwareSPI();
#else
   funcToInitSoftwareSPI();
#endif
}

And in my library.h, I wrote:

#ifndef __LIB_H
#define __LIB_H

#define HARDWARE_SPI

void LibraryInit();

#endif

Then I think if user define #define HARDWARE_SPI in the target project, the library will run hardware SPI part. If not, software SPI should be in use.

But after I build the project and added library.a and library.h into testing project, with library.h has no #define HARDWARE_SPI, the routine is still going into hardware SPI part. How can I build the library.a that can let user choose the function by writing #define in the header file?

1
Unrelated to your question, but don't use symbols with two leading underscores, or one leading underscore followed by an upper-case letter. Those symbols are reserved in all scopes for the compiler and standard library. - Some programmer dude
@Someprogrammerdude Got you! Thanks for teaching me some fundamental! - SoWaiSam

1 Answers

0
votes

The .a file is build before a user decides hard or soft spi, so you can't. You must build both codepaths. Is there an issue with providing the library as source?

Considering you're using an 8 bit mcu, I assume you don't want to mess with big abstractions with function pointers, therefore all selection of your code-path must happen in your provided header. If your compiler supports C99, you can place the functions that switch between the implementations inline in your header:

/* library.h */

#pragma once
void funcToInitHardwareSPI();
void funcToInitSoftwareSPI();

inline void LibraryInit()
{
#ifdef HARDWARE_SPI
   funcToInitHardwareSPI();
#else
   void funcToInitSoftwareSPI();
#endif
}

Considering both codepaths are now added to your library, you might want to compile it with each function in a separate section, and then remove all unused sections during linking.