Adding libraries that are out-of-tree to an application in CLI2

Hello folks,

I’d like to share my experience with adding libraries which are out-of-tree to an application program in mbed CLI2.

I had the following directory structure on a Linux machine and wanted to add the Clock library to the MyApp program.

/src
|
├── app
│   ├── os-2
│   └── os-6
|	    └──MyApp
|          ├── main.cpp
|          ├── CMakeLists.txt
|          └── mbed-os (symbolic link to /src/sys/6.16.0)
├── lib
│   ├── os-2
│   └── os-6
|	    └──Clock 
|          ├── include
|          |   └── Clock.h
|          └── source
|              └── Clock.cpp
└── sys
    ├── 2.0.165
    ├── 6.15.1
    ├── 6.16.0
    └── custom_targets

After a lot of struggle I came up with the following solution:

I created a CMakeLists.txt file in the Clock directory with the following content:

include_directories(
	${CMAKE_CURRENT_LIST_DIR}/include
)

list(APPEND app_sources
    ${CMAKE_CURRENT_LIST_DIR}/source/Clock.cpp
)

And then I used the following CMakeLists.txt file in the MyApp directory:

# Copyright (c) 2022 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.19.0)

set(MBED_PATH ${CMAKE_CURRENT_SOURCE_DIR}/mbed-os CACHE INTERNAL "")
set(MBED_CONFIG_PATH ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL "")
set(APP_TARGET MyApp)

include(${MBED_PATH}/tools/cmake/app.cmake)

project(${APP_TARGET})

add_subdirectory(${MBED_PATH})

list(APPEND app_sources main.cpp)

include(/src/lib/os-6/Clock/CMakeLists.txt)

add_executable(${APP_TARGET} ${app_sources})

target_link_libraries(${APP_TARGET} mbed-os)

mbed_set_post_build(${APP_TARGET})

option(VERBOSE_BUILD "Have a verbose build process")
if(VERBOSE_BUILD)
    set(CMAKE_VERBOSE_MAKEFILE ON)
endif()

This enables to easily add more libraries to the MyApp program by creating a similar CMakeLists.txt file in the given library’s directory and adding an additional line as below to the CMakeLists.txt file in the MyApp directory:

...
include(/src/lib/os-6/AnotherLibrary/CMakeLists.txt)
...

Maybe someone finds it useful.

Best regards,

Zoltan