1

lib1/CMakeLists.txt

add_library(lib1 STATIC
    lib1.cpp
    lib1.h
)
target_include_directories(lib1
    PRIVATE ../third
)
target_link_libraries(lib1
    PRIVATE third
)

CMakeLists.txt

add_subdirectory(lib1)

add_executable(exe
    main.cpp
)
target_link_libraries(exe
    PRIVATE lib1
)
target_include_directories(lib1_objs
    PRIVATE ../lib1
)

When I run make, it show this error

Scanning dependencies of target lib1
[ 25%] Building CXX object lib1/CMakeFiles/lib1.dir/lib1.cpp.o
[ 50%] Linking CXX static library liblib1.a
[ 50%] Built target lib1
Scanning dependencies of target a
[ 75%] Building CXX object CMakeFiles/a.dir/main.cpp.o
[100%] Linking CXX executable a
/usr/bin/ld: cannot find -lthird
collect2: error: ld returned 1 exit status

I only link lib-third PRIVATE in lib1/CMakeLists.txt, why 'exe' need link third?

Rhysol
  • 481
  • 1
  • 3
  • 12
  • Similar problem is stated here: https://stackoverflow.com/questions/36181626/cmake-linking-to-static-internal-library-without-exporting-it. It seems that CMake treats `target_link_libraries` for a STATIC library in a special way: Whatever publicity keyword is used, that linkage is propagated to the **shared** object (an executable or a shared library) which links with a static library. That behavior has a sense: when created, the library file `liblib1.a` isn't actually linked with `third` because static libraries are never linked. `Linking CXX static library liblib1.a` is not quite true. – Tsyvarev Aug 24 '20 at 11:13
  • @Tsyvarev So liblib1.a link libthird.a is not really added all content to liblib1.a? What happened after link libthird.a – Rhysol Aug 25 '20 at 02:04
  • "What happened after link `libthird.a`?" - This "linking" doesn't affect on content `liblib1.a` at all. The line `target_link_libraries(lib1 [keyword] third)` it only useful when other CMake **targets** link `lib1` **target**. For such every such target CMake propagates the linkage with `third` library. – Tsyvarev Aug 25 '20 at 14:12
  • I got it. Thank you so much! – Rhysol Aug 26 '20 at 08:09

0 Answers0