Here’s the structure of my project:
root
├── CMakeLists.txt
├── lib1
│ ├── CMakeLists.txt
│ └── lib1.cpp
├── lib2
│ ├── CMakeLists.txt
│ └── lib2.cpp
└── main.cpp
This is lib2/lib2.cpp
:
#include <iostream>
void lib2() {
std::cout << "lib2 run\n";
}
This is lib2/CMakeLists.txt
:
add_library(lib2 STATIC lib2.cpp)
This is lib1/lib1.cpp
, lib1()
calls the lib2()
function.
#include <iostream>
void lib2();
void lib1() {
std::cout << "lib1 run\n";
lib2();
}
This is lib1/CMakeLists.txt
,the scope is PRIVATE
add_library(lib1 STATIC lib1.cpp)
target_link_libraries(lib1 PRIVATE lib2)
This is the content of main.cpp
,main()
calls the lib1()
function.
void lib1();
int main(int argc, char *argv[]) {
lib1();
}
This is CMakeLists.txt
:
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:
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.