Linking the same library against two different targets

Hello!

I am working on a project on which a will be developing an application and bootloader for an embedded microcontroller. The project will be baremetal so no OS needs to be included. It is completely written in C.

There are a couple of libraries I will have to use in this project though, and these libraries will be used for both the application and the bootloader. Internally we have a “Framework” library, which contains many C building blocks for all kinds of things, next to that, the specific HAL of the microcontroller vendor will be included. In our current CMake structure, we build both these libraries with the add_library() function and then link it against the application we are building with target_link_libraries()

This works perfectly fine in simple cases, however I’m struggling to understand how I can properly use this in a project with mutliple targets which share these libraries. Of course we can use the same library and link it against multiple targets, however what do I do if need to compile a file or with different definitions or compile options between targets? Is the only way to compile two completely different libraries and then link the respective libraries to the targets? Are there any recommended best practices regarding this?

Here’s an example of the problem specifically:
Consider a configuration header file which is used for the HAL flash driver, it determines whether the driver is allowed to write in certain flash regions.

#ifndef R_FLASH_LP_CFG_H_
#define R_FLASH_LP_CFG_H_

#define FLASH_LP_CFG_PARAM_CHECKING_ENABLE (BSP_CFG_PARAM_CHECKING_ENABLE)

// NOTE: Only the bootloader should be allowed to program code flash
#ifdef BOOTLOADER
#define FLASH_LP_CFG_CODE_FLASH_PROGRAMMING_ENABLE (1)
#else
#define FLASH_LP_CFG_CODE_FLASH_PROGRAMMING_ENABLE (0)
#endif
#define FLASH_LP_CFG_DATA_FLASH_PROGRAMMING_ENABLE (1)

#endif /* R_FLASH_LP_CFG_H_ */

First I build the HAL Library for the application, the #ifdef BOOTLOADER symbol will evaluate to false, so that’s what the HAL library is built with. Then I want to create a separate target which uses the exact same HAL library, however now defined as BOOTLOADER. How would I approach this?

Thanks in advance!

Yes. There’s no restriction that source files can only be part of a single target. Per-source properties can’t distinguish between the target without generator expressions to tell them apart.