# Why didn't my use of \`target\_link\_libraries\` produce the expected result?

**URL:** https://discourse.cmake.org/t/why-didnt-my-use-of-target-link-libraries-produce-the-expected-result/11394
**Category:** Usage
**Tags:** os:linux, gen:makefiles
**Created:** [August 6, 2024, 2:22pm UTC](https://discourse.cmake.org/t/why-didnt-my-use-of-target-link-libraries-produce-the-expected-result/11394 "2024-08-06T14:22:19Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![lamb007](https://discourse.cmake.org/user_avatar/discourse.cmake.org/lamb007/32/4836_2.png) [@lamb007](https://discourse.cmake.org/u/lamb007)
#### Post date: [August 6, 2024, 2:22pm UTC](https://discourse.cmake.org/t/why-didnt-my-use-of-target-link-libraries-produce-the-expected-result/11394/1 "2024-08-06T14:22:19Z")

</div>

Here’s the structure of my project:

```auto
root
├── CMakeLists.txt
├── lib1
│ ├── CMakeLists.txt
│ └── lib1.cpp
├── lib2
│ ├── CMakeLists.txt
│ └── lib2.cpp
└── main.cpp

```

This is `lib2/lib2.cpp`:

```cpp
#include <iostream>
void lib2() {
    std::cout << "lib2 run\n";
}

```

This is `lib2/CMakeLists.txt`:

```cmake
add_library(lib2 STATIC lib2.cpp)

```

This is `lib1/lib1.cpp`, `lib1()` calls the `lib2()` function.

```cpp
#include <iostream>

void lib2();
void lib1() {
    std::cout << "lib1 run\n";
    lib2();
}

```

This is `lib1/CMakeLists.txt`，the scope is PRIVATE

```cmake
add_library(lib1 STATIC lib1.cpp)
target_link_libraries(lib1 PRIVATE lib2)

```

This is the content of `main.cpp`,`main()` calls the `lib1()` function.

```cpp
void lib1();
int main(int argc, char *argv[]) {
   lib1();
}

```

This is `CMakeLists.txt`:

```cmake
cmake_minimum_required(VERSION 3.12)
project(Example)

add_subdirectory(lib2)
add_subdirectory(lib1)

add_executable(main main.cpp)
target_link_libraries(main
    PRIVATE lib1
)

```

My intention is: subproject lib2 creates a static library `lib2`, and `lib1` creates a static library `lib1` with `lib2` linked to it and the scope used is `PRIVATE`, so `lib2` should not be propagated to the target(`main` in above example) that depends on `lib1`. Although `lib1` links to `lib2`, static libraries do not link to the libraries on which they depend, so `main` should not link to `lib2`. However, when I build the project and run `main`, the result is:

```auto
lib1 run
lib2 run

```

which indicates that `main` correctly links to `lib2`. Why is this the case?  
I am new to CMake and have already spent a day on this problem. Thank you for taking the time.
