How to split the application to libraries using CMake

Hello, I am using the nRF Connect SDK version 2.1.2. Working on a prototype using nRF52840-DK

I created the project using the `blinky` as the template. In the project, I would like to have a library called led and link the library to the CMake target app so I have the following folder structure

|--- CMakeLists.txt            // 1. This is the default CMake file generated by default

|--- src
       |
       |--- led                          // 2. Added a subfolder under the folder src, trying to build a library and include the library in the target app in the default CMake file that is in the project root
       |       |- CMakeLists.txt  // 3. I am adding an extra CMake file to config the led library
       |       |- led.h
       |       |- led.cpp
       |--- main.cpp                // 4. Modified the default main.c to main.cpp since I have the CONFIG_CPLUSPLUS=y in the project KConfig file
So the content of the CMake Lists.txt (3) in the led subfolder is:
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})

add_library(led
  "${CMAKE_CURRENT_SOURCE_DIR}/led.h"
  "${CMAKE_CURRENT_SOURCE_DIR}/led.cpp"
)

target_include_directories(led PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")
target_compile_definitions(led PRIVATE LED_VERSION=0.1.0)
The modified CMakeLists.txt (1) in the root folder is:
# SPDX-License-Identifier: Apache-2.0
# https://cliutils.gitlab.io/modern-cmake/
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(sensors VERSION 0.1.0)


#set_property(GLOBAL PROPERTY USE_FOLDERS ON)

# app
list(APPEND PATH_HEADER "src")

# led
set(PATH_LED src/led)
add_subdirectory(${PATH_LED})
list(APPEND FEATURES led)
# link led
list(APPEND PATH_HEADER ${PATH_LED})
target_link_directories(app PRIVATE ${PATH_LED})
target_link_libraries(app PRIVATE ${FEATURES})

target_include_directories(app PRIVATE ${PATH_HEADER})
target_sources(app PRIVATE src/main.cpp)
The led.h/cpp is pretty much empty:
header file:
#pragma once

class led
{
  public:
  bool enable = false;
  void toString() const;
};
and the cpp file
#include "led.h"
#include <zephyr/zephyr.h>

void led::toString() const
{
  // LED_VERSION is defined in the CMake
  printk("is led enabled? %d, version %s", this->enable, LED_VERSION);
}
Eventually, when I rebuild the CMake I have the following error:
d:\projects\Nordic\2.1.1\L2_DeviceTree\src\led\led.cpp:2:10: fatal error: zephyr/zephyr.h: No such file or directory
    2 | #include <zephyr/zephyr.h>
      |          ^~~~~~~~~~~~~~~~~
compilation terminated.
It seems the led library is unable to find the zephyr headers, I think the Zephyr configuration should be inherited from the root folder's CMake file, but it seems that is not the case, any suggestions to fix the compile error. I feel like I missed something in the CMake, but I just can not find what is missing Disappointed
Parents Reply Children
No Data
Related