How to create cmake library that expects an external header file

184 views Asked by At

I feel like I'm missing some key idea with this one.

I have a library that I'd like to create a CMakeLists.txt file for. I want to link against it with different applications.

This library expects a conf.h file to be defined. The application has to provide this. The library expects it. What is this relationship called?

My current solution in CMakeLists.txt is to have a variable like:

...
target_include_directories(lib PUBLIC
${CONF_DIR}
)

And then have CONF_DIR be defined by the application. This is uncool, because I can't have multiple applications linking against it.

The only other alternative is to keep a copy of the entire source library inside the application folder, which is also uncool.

I'm looking to maximize reusability. How do I approach this?

Side note: For anyone who's familiar, the library in question is STM32Cube's HAL library, and the pesky file is stm32h7xx_hal_conf.h.

enter image description here

2

There are 2 answers

0
arrowd On

You can't do anything about this, so you'll have to copy the library code.

The header file is used during library compilation stage, so its code ends up being hardwired into the final binary. Because of this, if you want to change some parameters from the header, you need to recompile the library from scratch.

Ideally, the library should be rewritten in such way, that all parameters that are contained in the header can be set up dynamically, during the runtime, using some additional configuration API.

0
Armandas On

This is a very common approach, when a library requires configuration. FreeRTOS would be another example.

I don't see the issue with modifying the target_include_directories for the library from the App's CMakeLists.txt.

Usually, I create a function to handle the library set-up. The call site would look something like this:

add_stm32_hal_lib(
    PATH drivers/STM32H7xx_HAL_Driver
    EXTRA_INCLUDES path/to/config
)
# ...
target_link_libraries(app PUBLIC stm32_hal)

The contents of the EXTRA_INCLUDES parameter get shoved into target_include_directories of the static library.