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
22if(DEFINED CMAKE_C_COMPILER_TARGET)
23  set(target_flag "--target=${CMAKE_C_COMPILER_TARGET}")
24endif()
25
26set(external_project_cflags
27  "${target_flag} ${includes} ${definitions} ${options} ${system_includes}"
28  )
29
30include(ExternalProject)
31
32# Add an external project to be able download and build the third
33# party library. In this case downloading is not necessary as it has
34# been committed to the repository.
35set(mylib_src_dir   ${CMAKE_CURRENT_SOURCE_DIR}/mylib)
36set(mylib_build_dir ${CMAKE_CURRENT_BINARY_DIR}/mylib)
37
38set(MYLIB_LIB_DIR     ${mylib_build_dir}/lib)
39set(MYLIB_INCLUDE_DIR ${mylib_src_dir}/include)
40
41if(CMAKE_GENERATOR STREQUAL "Unix Makefiles")
42# https://www.gnu.org/software/make/manual/html_node/MAKE-Variable.html
43set(submake "$(MAKE)")
44else() # Obviously no MAKEFLAGS. Let's hope a "make" can be found somewhere.
45set(submake "make")
46endif()
47
48ExternalProject_Add(
49  mylib_project                 # Name for custom target
50  PREFIX     ${mylib_build_dir} # Root dir for entire project
51  SOURCE_DIR ${mylib_src_dir}
52  BINARY_DIR ${mylib_src_dir} # This particular build system is invoked from the root
53  CONFIGURE_COMMAND ""    # Skip configuring the project, e.g. with autoconf
54  BUILD_COMMAND
55  ${submake}
56  PREFIX=${mylib_build_dir}
57  CC=${CMAKE_C_COMPILER}
58  AR=${CMAKE_AR}
59  CFLAGS=${external_project_cflags}
60  INSTALL_COMMAND ""      # This particular build system has no install command
61  BUILD_BYPRODUCTS ${MYLIB_LIB_DIR}/libmylib.a
62  )
63
64# Create a wrapper CMake library that our app can link with
65add_library(mylib_lib STATIC IMPORTED GLOBAL)
66add_dependencies(
67  mylib_lib
68  mylib_project
69  )
70set_target_properties(mylib_lib PROPERTIES IMPORTED_LOCATION             ${MYLIB_LIB_DIR}/libmylib.a)
71set_target_properties(mylib_lib PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${MYLIB_INCLUDE_DIR})
72
73target_link_libraries(app PUBLIC mylib_lib)
74