modules: nanopb: Add helper function to generate sources

Introduce a helper function zephyr_nanopb_sources to generate
source files and add these to a target.

Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
This commit is contained in:
Pieter De Gendt 2023-09-14 20:02:53 +02:00 committed by Carles Cufí
commit 0357b4d4f5
3 changed files with 40 additions and 22 deletions

View file

@ -6,25 +6,15 @@ if(CONFIG_NANOPB)
set(NANOPB_DIR ${ZEPHYR_CURRENT_MODULE_DIR})
find_program(PROTOC protoc)
if(NOT PROTOC)
message(FATAL_ERROR "'protoc' not found, please ensure protoc is installed\
and in path. See https://docs.zephyrproject.org/latest/samples/modules/nanopb/README.html")
endif()
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${NANOPB_DIR}/extra)
find_package(Nanopb REQUIRED)
zephyr_library()
zephyr_include_directories(${NANOPB_DIR})
zephyr_library_sources(
${NANOPB_DIR}/pb_common.c
${NANOPB_DIR}/pb_encode.c
${NANOPB_DIR}/pb_decode.c
)
zephyr_include_directories(${NANOPB_DIR})
zephyr_compile_definitions(
PB_MAX_REQUIRED_FIELDS=${CONFIG_NANOPB_MAX_REQUIRED_FIELDS})

View file

@ -0,0 +1,33 @@
# Copyright (c) 2023, Basalte bv
#
# SPDX-License-Identifier: Apache-2.0
include_guard(GLOBAL)
list(APPEND CMAKE_MODULE_PATH ${ZEPHYR_NANOPB_MODULE_DIR}/extra)
find_program(PROTOC protoc)
if(NOT PROTOC)
message(FATAL_ERROR "'protoc' not found, please ensure protoc is installed\
and in path. See https://docs.zephyrproject.org/latest/samples/modules/nanopb/README.html")
endif()
find_package(Nanopb REQUIRED)
# Usage:
# list(APPEND CMAKE_MODULE_PATH ${ZEPHYR_BASE}/modules/nanopb)
# include(nanopb)
#
# zephyr_nanopb_sources(<target> <proto-files>)
#
# Generate source and header files from provided .proto files and
# add these as sources to the specified target.
function(zephyr_nanopb_sources target)
# Turn off the default nanopb behavior
set(NANOPB_GENERATE_CPP_STANDALONE OFF)
nanopb_generate_cpp(proto_srcs proto_hdrs RELPATH ${CMAKE_CURRENT_SOURCE_DIR} ${ARGN})
target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
target_sources(${target} PRIVATE ${proto_srcs} ${proto_hdrs})
endfunction()

View file

@ -5,15 +5,10 @@ cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(nanopb_sample)
# Note that here, we're adding CMAKE_SOURCE_DIR to the include path for nanopb.
# This is needed because the below call to nanopb_generate_cpp() is using
# 'RELPATH .'
set(NANOPB_OPTIONS "-I${CMAKE_SOURCE_DIR}")
nanopb_generate_cpp(proto_sources proto_headers RELPATH .
src/simple.proto
)
# we need to be able to include generated header files
zephyr_library_include_directories(${CMAKE_CURRENT_BINARY_DIR})
list(APPEND CMAKE_MODULE_PATH ${ZEPHYR_BASE}/modules/nanopb)
include(nanopb)
zephyr_nanopb_sources(app src/simple.proto)
FILE(GLOB app_sources src/*.c)
target_sources(app PRIVATE ${proto_sources} ${app_sources})
target_sources(app PRIVATE ${app_sources})