2 minute read

Use-case: You have a library as source code, want to install it on your system (user-/system-wide), and then make use of it from another place/folder/repo.

Step 1: Install the library

Assume the library to install is located at /home/bob/myLibrary and should be available under the /home/bob/lib folder.

cd ~/myLibrary
cmake -B build -DCMAKE_INSTALL_PREFIX=/home/bob/lib/myLibrary
cd build
cmake --build . --target install 

What will be created under /home/bob/lib/myLibrary is dependent on the library itself (in its own CMakeLists.txt it can define what kind of folder structure will be created).

As an example: The QuantLib library creates by default this kind of structure:

/home/bob/lib/QuantLib/
  bin/...
  include/ql/...
  lib/
    libQuantLib.so
    ....

Step 2: Make use of the installed library within your other project

You can make use of the installed library by using the installed headers (e.g. some hpp files under include/ql) as well as linking against the library (e.g. against lib/libQuantLib.so)`.

This is best accomplished by creating a separate target within CMake for the precompiled library. We will make use of the IMPORTED tag as well STATIC/SHARED depending on the library type (e.g. SHARED for .so). By setting properties we can let it know of the artifact (e.g. .so file), and the include directory.

An example CMakeLists.txt making use of the above given installed QuantLib example library:

# file: /home/bob/testRepo/CMakeLists.txt
cmake_minimum_required(VERSION 3.20)
project(Test)

add_library(QuantLib SHARED IMPORTED)
set_target_properties(QuantLib PROPERTIES
  IMPORTED_LOCATION             "/home/bob/lib/QuantLib/lib/libQuantLib.so"
  INTERFACE_INCLUDE_DIRECTORIES "/home/bob/lib/QuantLib/include"
)

add_executable(main)
target_sources(main PRIVATE main.cpp)
target_link_libraries(main PRIVATE QuantLib)


Source: https://stackoverflow.com/a/67889100/10774817