2

I am compiling multiple C++ applications (app1,app2) linking libif. libif interfaces a library which is available in two versions (libV1 libV2).

Depending on the application that links to it I need libif to interface libV1 (for app1) xor libV2 (for app2).

The following code aims to describe the situation.

add_library(libV1 STATIC IMPORTED GLOBAL)

...
add_library(libV2 STATIC IMPORTED GLOBAL)
...

#app1
add_library(libif ${other_sources})
target_link_libraries(libif INTERFACE libV1)
add_executable(app1 ${sources})
target_link_libraries(app1 PRIVATE libif)

#app2
add_library(libif ${other_sources})
target_link_libraries(libif INTERFACE libV2)
add_executable(app2 ${sources})
target_link_libraries(app2 PRIVATE libif)

The following code aims to describe the desired result:

add_library(libV1 STATIC IMPORTED GLOBAL)
...
add_library(libV2 STATIC IMPORTED GLOBAL)
...

add_library(libif ${other_sources})
target_link_libraries(libif INTERFACE $<app1_consumes_me:libV1> $<app2_consumes_me:libV2>)

add_executable(app1 ${sources})
target_link_libraries(app1 PRIVATE libif)

add_executable(app2 ${sources})
target_link_libraries(app2 PRIVATE libif)

Is there any Idiom for saying "CMake link/interface a library depending on the target which consumes it."?

I think the simplest - although not "beautiful" solution will need me to create 2 libif versions: "libif_libV1" and "libif_libV2". Which then would spawn n different Versions of any depending Library too. But is there any better way? Is this a very rare usecase?

I already assume of generator-expressions not being the right tool for the job - but maybe there is a macro/function dedicated to this situation.

bigla
  • 88
  • 6
  • 1
    "Is there any Idiom for saying "CMake link/interface a library depending on the target which consumes it."?" - No, CMake has no such idiom. Every library target - be it normal or IMPORTED - represents a concept, which is **consumed** in the same way, irrespectively to the consumer. I agree, that this model is inconvenient in some cases, but even this "simple" model has quite complex implementation in CMake. – Tsyvarev Jul 29 '20 at 13:14
  • Well at least some "loose coupling" as a concept would be of help - something like "don't link this library BEFORE/AFTER other libraries are linked". In that way I'd be able to make sure undefined symbols are resolved correctly on any platform. Would add_dependencies accomplish this? – bigla Jul 29 '20 at 14:11

0 Answers0