CodeBlanks Logo Icon CodeBlanks

CMakeLists.txt

Learn to write CMakeLists.txt.

CMakeLists.txt structure

Every source directory root has a CMakeLists.txt. This file contains CMake commands. The most common commands are: add_executable (executable target), add_library (library target), target_link_libraries (link a library to a target) and target_include_directories (header search path).

Example: add_library(mylib STATIC utils.cpp) defines a static library. target_link_libraries(myapp PRIVATE mylib) links mylib to the myapp target. PRIVATE means the dependency belongs only to this target. These commands build relationships between targets.

target_link_libraries

The target_link_libraries(target SCOPE library) command links a library to a target. The scope is one of three: PRIVATE (only this target), PUBLIC (target and its users), INTERFACE (only users).

Example: target_link_libraries(myapp PRIVATE mylib). Here myapp uses mylib but another target using myapp does not see mylib. If the library headers are also exposed, use PUBLIC. This distinction ensures dependencies propagate correctly and prevents unnecessary linking.

Practice Link a library to a target

Write a CMakeLists.txt. Define a static library with add_library(mylib STATIC utils.cpp). Define an executable target with add_executable(myapp main.cpp). Link mylib to myapp with target_link_libraries(myapp PRIVATE mylib).

Starter code

main.cpp
# CMakeLists.txt
# Add add_library, add_executable and target_link_libraries

Sample solution

main.cpp
add_library(mylib STATIC utils.cpp)
add_executable(myapp main.cpp)
target_link_libraries(myapp PRIVATE mylib)

Expected output

Target ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the executable command

Question
____(myapp main.cpp)
Answer
add_executable(myapp main.cpp)

Explanation: add_executable defines an executable target.

2 What does add_executable do?

  • Selects a compiler
  • Defines a library
  • Adds a header path
  • Defines an executable target Correct answer

Explanation: add_executable defines an executable target from source files.

3 Match the command to its role

Term Meaning
add_library Library target
add_executable Executable target
target_link_libraries Links a library
target_include_directories Adds header path

All lessons in Advanced