Adding Libraries

Introduction

CMake makes it easy to link libraries to your project. Libraries can be system libraries, third-party libraries, or libraries you build yourself.

Key Concepts

  • find_package(): Finds a system library or package.
  • add_library(): Creates a library target.
  • target_link_libraries(): Links libraries to a target.

Code Sample

You can continue using the files from the previous chapter.

  1. Create a new file my_library.cpp with some dummy code.
void my_library_func() {
  // noop
}
  1. Edit the CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(HelloWorld)

add_executable(HelloWorld main.cpp)

set(MY_VARIABLE "Hello, CMake!")
message(STATUS "MY_VARIABLE is set to ${MY_VARIABLE}")

option(ENABLE_FEATURE "Enable a feature" ON)
if(ENABLE_FEATURE)
    message(STATUS "Feature is enabled")
else()
    message(STATUS "Feature is disabled")
endif()

# --- ADD THESE LINES ---
find_package(Threads REQUIRED)
target_link_libraries(HelloWorld PRIVATE Threads::Threads)

add_library(MyLibrary STATIC my_library.cpp)
target_link_libraries(HelloWorld PRIVATE MyLibrary)

Quiz

What does find_package do?

find_package locates a system library or package. If REQUIRED is specified and the package isn’t found, CMake will stop with an error.

How do you create a static library in CMake?

You can create a static library using add_library(MyLibrary STATIC ...).

What is the purpose of target_link_libraries?

target_link_libraries links the specified libraries to your executable or library target.