1

I have 2 static libraries in two different folders: libA and libB

  • libB must include libA

My main CMakeLists.txt is:

add_subdirectory(libA)
add_subdirectory(libB)

My first mistake was to think linking libA in libB would include it but it isn't:

target_link_libraries(${PROJECT_NAME} PUBLIC libA::libA)

I get undefined reference to some libA's functions when I try to use libB in an app.

Alexis
  • 2,136
  • 2
  • 19
  • 47

2 Answers2

0

If you control the builds for both libA and libB, you can solve this by creating OBJECT libraries libA-obj and libB-obj. You would then link libA-obj to libA and then link both object libraries to libB.


Here's a more detailed sketch

cmake_minimum_required(VERSION 3.22)
project(example)

# ...

# Can be in subdirectory
add_library(libA-obj ${libA-srcs})
add_library(libA)
target_link_libraries(libA PUBLIC libA-obj)

# Can be in subdirectory
add_library(libB-obj ${libB-srcs})
add_library(libB)
target_link_libraries(libB PUBLIC libB-obj libA-obj)

# Can be in parent directory
add_executable(app ${app-srcs})
target_link_libraries(app PRIVATE libB)
Alex Reinking
  • 16,724
  • 5
  • 52
  • 86
  • Thanks but how? I'm completely lost with all the examples that do only partially what I want. I have `add_library(objlib OBJECT ${SRC})` in each CMakeLists.txt but how about the top one? – Alexis Dec 20 '21 at 09:47
  • @Alexis - I've updated my answer to include a more detailed sketch – Alex Reinking Dec 20 '21 at 17:54
  • What if I don't need static library for libA? Also, what if there is a third libC that is nested? libA->libB-libC? I don't want to reference libA in libC since it's already in libB. – Alexis Dec 21 '21 at 06:33
0

You can add the object files that comprise libA to the sources of libB to include them:

target_sources(LibB PRIVATE $<TARGET_OBJECTS:LibA>)
Botje
  • 26,269
  • 3
  • 31
  • 41