Using static libraries on a Zephyr RTOS Project

Zephyr RTOS uses the CMake tools to compile and build it’s projects. Also all provided modules use CMake files or are modified to work with CMake files so that they integrate with the Zephyr RTOS.

On it’s own, CMake is a massive tool and takes some time to hold all the concepts, and so to do a simple thing like adding a third-party static library to a Zephyr RTOS project can be a complicated task when not all sides of CMake tool are understood…

Anyway, a quick tip, for those, that like me, wanted to add static libraries to a Zephyr RTOS project:

Basically at the Zephyr project root directory there is a CMakeLists.txt file. To add our libraries we must modify this file. For example a standard Zephyr CMakeLists.txt file may look like:

# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.13.1)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(blinky)

target_sources(app PRIVATE src/main.c)

Let’s say now that we want to link our project with a third party library provided in a static library format: OtherLib.a.

At the root of the project we might, or should, create a directory called, for example, lib, and copy our lib, our libs files to that directory. And then modify the CMakeLists.txt file to look like:

# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.13.1)

set(LIB_DIR  ${CMAKE_CURRENT_SOURCE_DIR}/lib)

find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(complex_blinky)

FILE(GLOB app_sources src/*.c)
target_sources(app PRIVATE ${app_sources})

add_library(other3party_lib STATIC IMPORTED GLOBAL)

set_target_properties(other3party_lib PROPERTIES IMPORTED_LOCATION ${LIB_DIR}/OtherLib.a)

target_link_libraries(app PUBLIC other3party_lib)

Excluding the line FILE(GLOB app_sources src/*.c) that is used to add all C files on the src directory to the project, the other bold lines, specifically the last but one, are used to add the static library to the project.

If multiple libraries are needed to link, the set_target_properties line should be duplicated and modified to point to each library that is needed to link to the project.

And that’s it.

2 thoughts on “Using static libraries on a Zephyr RTOS Project

  1. I have a static library in the format: lib.a
    Can this process be followed for linking my static library?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.