cpp_enthusiast
cpp_enthusiast

Reputation: 1299

cmake - two targets that depends on single static library that should be compiled based on the target that is being built

I have a static library and two target executables, let's call them libA, EXE1, EXE2.

libA has pre-processor macros which needs to be enabled or disabled and another static library which needs to be linked or ignored based on the target executable that I am building.

Let's say, if I am building EXE1. Then I need to enable the macros in libA and link another static library to it.

If I am building EXE2, I need to disabled the macros in libA and don't link to another library.

I am confused on how to solve this issue. Please kindly help in solving this issue.

Upvotes: 1

Views: 110

Answers (1)

Botje
Botje

Reputation: 31113

You can make use of an interface library as follows:

cmake_minimum_required(VERSION 3.10)
project(test)

add_library(libA INTERFACE)
target_sources(libA INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/liba.c)

add_executable(exe1 exe1.c)
target_link_libraries(exe1 libA)
target_compile_definitions(exe1 PUBLIC -DENABLE_THE_MACROS)

add_executable(exe2 exe2.c)
target_link_libraries(exe2 libA libOtherStatic)
target_compile_definitions(exe1 PUBLIC -DDISABLE_THE_MACROS)

libA is a "virtual" target that does not produce any output, but it can be linked to other targets (here exe1 and exe2) Any target that links to libA will automatically receive the sources of libA as well. Note that I had to make the path absolute to prevent a warning.

Upvotes: 3

Related Questions