How to create a static library on nRF Connect SDK/Zephyr

Hi,

I am using nrF52840 with nRF Connect, Visual Code Studio (Zephyr) 

Is there any guide or a tutorial with an example that shows how to create a static library on nRF Connect SDK/Zephyr?

There are some topics opened related to this, but none of them have the complete solution.

Please if you can explain in detail, it would help everyone a lot. Thanks

Parents Reply
  • Hello Håkon and Akif,

    I feel like that sample does a lot more than what's necessary to simply include a lib. Wouldn't these lines added to the cmake be enough?

    zephyr_include_directories(src/lib)
    target_sources(app PRIVATE src/lib/libname.c)
    

    I remember having a hard time implementing one my self, and that sample confused me more than it helped.

    Please correct me if I'm wrong, but it works for me!

Children
  • To include a lib and to create a lib are two different operations. The below sample shows both.

    If you want to include a precompiled static library, you can shorten the whole thing, similar to this:

    # SPDX-License-Identifier: Apache-2.0
    
    cmake_minimum_required(VERSION 3.20.0)
    find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
    project(external_lib)
    
    target_sources(app PRIVATE src/main.c)
    
    include(ExternalProject)
    
    # Add an external project to be able download and build the third
    # party library. In this case downloading is not necessary as it has
    # been committed to the repository.
    
    set(MYLIB_LIB_DIR     ${CMAKE_CURRENT_SOURCE_DIR}/lib)
    set(MYLIB_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/mylib/include)
    
    # Create a wrapper CMake library that our app can link with
    add_library(mylib_lib STATIC IMPORTED GLOBAL)
    add_dependencies(
      mylib_lib
      mylib_project
      )
    set_target_properties(mylib_lib PROPERTIES IMPORTED_LOCATION             ${MYLIB_LIB_DIR}/libmylib.a)
    set_target_properties(mylib_lib PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${MYLIB_INCLUDE_DIR})
    
    target_link_libraries(app PUBLIC mylib_lib)

     

    Kind regards,

    Håkon

Related