1# SPDX-License-Identifier: Apache-2.0 2 3cmake_minimum_required(VERSION 3.20.0) 4find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) 5project(external_lib) 6 7target_sources(app PRIVATE src/main.c) 8 9# The external static library that we are linking with does not know 10# how to build for this platform so we export all the flags used in 11# this zephyr build to the external build system. 12# 13# Other external build systems may be self-contained enough that they 14# do not need any build information from zephyr. Or they may be 15# incompatible with certain zephyr options and need them to be 16# filtered out. 17zephyr_get_include_directories_for_lang_as_string( C includes) 18zephyr_get_system_include_directories_for_lang_as_string(C system_includes) 19zephyr_get_compile_definitions_for_lang_as_string( C definitions) 20zephyr_get_compile_options_for_lang_as_string( C options) 21 22set(external_project_cflags 23 "${includes} ${definitions} ${options} ${system_includes}" 24 ) 25 26include(ExternalProject) 27 28# Add an external project to be able download and build the third 29# party library. In this case downloading is not necessary as it has 30# been committed to the repository. 31set(mylib_src_dir ${CMAKE_CURRENT_SOURCE_DIR}/mylib) 32set(mylib_build_dir ${CMAKE_CURRENT_BINARY_DIR}/mylib) 33 34set(MYLIB_LIB_DIR ${mylib_build_dir}/lib) 35set(MYLIB_INCLUDE_DIR ${mylib_src_dir}/include) 36 37if(CMAKE_GENERATOR STREQUAL "Unix Makefiles") 38# https://www.gnu.org/software/make/manual/html_node/MAKE-Variable.html 39set(submake "$(MAKE)") 40else() # Obviously no MAKEFLAGS. Let's hope a "make" can be found somewhere. 41set(submake "make") 42endif() 43 44ExternalProject_Add( 45 mylib_project # Name for custom target 46 PREFIX ${mylib_build_dir} # Root dir for entire project 47 SOURCE_DIR ${mylib_src_dir} 48 BINARY_DIR ${mylib_src_dir} # This particular build system is invoked from the root 49 CONFIGURE_COMMAND "" # Skip configuring the project, e.g. with autoconf 50 BUILD_COMMAND 51 ${submake} 52 PREFIX=${mylib_build_dir} 53 CC=${CMAKE_C_COMPILER} 54 AR=${CMAKE_AR} 55 CFLAGS=${external_project_cflags} 56 INSTALL_COMMAND "" # This particular build system has no install command 57 BUILD_BYPRODUCTS ${MYLIB_LIB_DIR}/libmylib.a 58 ) 59 60# Create a wrapper CMake library that our app can link with 61add_library(mylib_lib STATIC IMPORTED GLOBAL) 62add_dependencies( 63 mylib_lib 64 mylib_project 65 ) 66set_target_properties(mylib_lib PROPERTIES IMPORTED_LOCATION ${MYLIB_LIB_DIR}/libmylib.a) 67set_target_properties(mylib_lib PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${MYLIB_INCLUDE_DIR}) 68 69target_link_libraries(app PUBLIC mylib_lib) 70