Issue
I am new to CMake and I am attempting to link libraries that are generated in the same project. The (simplified) project structure looks like this:
MyProject
├── CMakeLists.txt
├── Library1
│ └── CMakeLists.txt
│ └── include
│ └── foo.h
│ └── bar.h
│ └── src
│ └── foo.cpp
│ └── bar.cpp
├── Library2
│ └── CMakeLists.txt
│ └── include
│ └── baz.h
│ └── src
│ └── baz.cpp
CMakeLists.txt:
cmake_minimum_required (VERSION 3.17.0)
project(MyProject)
option(BUILD_SHARED_LIBS ON)
add_subdirectory(Library1)
add_subdirectory(Library2)
Library1/CMakeLists.txt:
project(Library1)
add_library(library1
src/foo.cpp
src/bar.cpp
)
target_include_directories(library1 PUBLIC
${CMAKE_SOURCE_DIR}/Library1/include
)
Library2/CMakeLists.txt:
project(Library2)
add_library(library2
src/baz.cpp
)
target_include_directories(library2 PUBLIC
${CMAKE_SOURCE_DIR}/Library1/include
${CMAKE_SOURCE_DIR}/Library2/include
)
find_library(LIB1 library1 HINTS ${CMAKE_SOURCE_DIR}/Library1)
target_link_libraries(library2 PUBLIC LIB1)
If I run cmake MyProject
I'll get this error:
CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
LIB1
linked by target 'library2' in directory 'MyProject/Library2'
--- Generating done
CMake Generate step failed. Build files cannot be regenerated correctly.
How do I link library2
to library1
when the library1
target won't be generated until after cmake --build MyProject
? Or is this not the correct way to be structuring this project?
Solution
This code is wrong.
find_library(LIB1 library1 HINTS ${CMAKE_SOURCE_DIR}/Library1)
target_link_libraries(library2 PUBLIC LIB1)
In the project you have presented you do not need to find
any library. It's already part of your build.
To fix your problem just link the library:
target_link_libraries(library2 PUBLIC library1)
TLDR explanation of when to use find_*
commands:
CMake offers a host of find_*
commands that are useful when working with package managers, SDKs, etc. that have installed pre-built
binaries on your computer.
In this case it's not needed since library1
is already part of your project. Why would CMake need to find
something it created/defined?
Answered By - jpr42 Answer Checked By - Pedro (WPSolving Volunteer)