Skip to content

Creating and using static libraries

Felipe Torrezan edited this page Jan 28, 2024 · 5 revisions

Introduction

This interactive example describes the configuration details for when, in a CMake project, an executable target make use of an user library.

Helpful Resources

Tutorial

When a project complexity increases, it might make sense to break down the complexity into multiple targets such as an executable along one or more user libraries. In such cases, organizing libraries in subdirectories is a good practice. These subdirectories usually contain their own CMakeLists.txt which are later consumed by an executable target. A CMake project example like this is provided at:

Project files
lib/inc/crc32.h
lib/src/crc32.c
lib/CMakeLists.txt
CMakeLists.txt
main.c
  • The main() function uses the library's crc32() function.

Tasks

Prepare the library by filling the missing information in lib/CMakeLists.txt (click to show/hide answers):

TODO 1: Add the `lib` library target
add_library(lib)
TODO 2: Configure the `lib` library sources
target_sources(lib PRIVATE src/crc32.c)
TODO 3: Using the `PUBLIC` scope, expose the `lib` headers (inc) to other targets
target_include_directories(lib PUBLIC inc)

In the application's CMakeLists.txt perform the following tasks:

TODO 4: Add the `lib` subdirectory (contains the `lib` target)
add_subdirectory(lib)
TODO 5: Link the `lib` library target against the `libs` executable target
target_link_libraries(libs lib)

Finally, build and test the project. Refer to the tutorial for more information.

Clone this wiki locally