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

Kyle Edwards kyle.edwards at kitware.com
Tue Jul 2 09:44:32 EDT 2019


On Tue, 2019-07-02 at 14:18 +0200, ugesh reddy wrote:
> Hello,
> 
> I couldn't find any solution's for this problem even after posting
> the question on Reddit/stack overflow, so I am posting it here.
> 
> My question is as follows:
> 
> 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 don't want to create two targets with same source files.

I'm sorry to say it, but creating two targets is actually exactly what
you want to do here. If your concern is code duplication, you can make
the code much shorter by using variables. Example:

set(libA_SRCS
  src1.c
  src2.c
  src3.c
  # lots of other sources...
  )
add_library(libA1 STATIC ${libA_SRCS})
target_link_libraries(libA1 otherlib)
add_library(libA2 STATIC ${libA_SRCS})

Kyle


More information about the CMake mailing list