Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8013

SDK • Re: Controlling cmake behaviour/output using -Dvar=value

$
0
0
The main thing to remember is '-Dname=whatever' on the command line only sets a variable within the 'CMakeLists.txt'. It will not automatically get passed on to your C code. For example '-DSEND_MESSAGE=' will set '${SEND_MESSAGE}'.

To pass that into the C code you need to add -
  • target_compile_definitions(${PROJECT} PRIVATE name="${SEND_MESSAGE}")
or
  • target_compile_options(${PROJECT} PRIVATE -Dname="${SEND_MESSAGE}")
Both will effectively provide '#define name ${SEND_MESSAGE}' for the C code.

Code:

set(PROJECT cmake-arguments)cmake_minimum_required(VERSION 3.12)include($ENV{PICO_SDK_PATH}/external/pico_sdk_import.cmake)project(${PROJECT} C CXX ASM)pico_sdk_init()add_executable(${PROJECT} main.c)if ("${SEND_MESSAGE}" STREQUAL "")   message(FATAL_ERROR "No '-DSEND_MESSAGE=' specified for 'cmake'")endif()target_compile_definitions(${PROJECT} PRIVATE  SEND_MESSAGE="${SEND_MESSAGE}")target_link_libraries(${PROJECT} pico_stdlib)target_compile_options(${PROJECT} PRIVATE -Wall -Werror)pico_add_extra_outputs(${PROJECT})pico_enable_stdio_usb(${PROJECT}  1)pico_enable_stdio_uart(${PROJECT} 0)pico_set_binary_type(${PROJECT} no_flash)

Code:

#include <stdio.h>#include "pico/stdlib.h"int main(void) {    stdio_init_all();    while (true) {       printf("%s\n", SEND_MESSAGE);       sleep_ms(1000);    }}

Code:

pi@Pi4B:~/mypico/cmake-arguments $ lsCMakeLists.txt  main.cpi@Pi4B:~/mypico/cmake-arguments $ cmake -S . -B build -DSEND_MESSAGE="Hello World"...pi@Pi4B:~/mypico/cmake-arguments $ cmake --build build...pi@Pi4B:~/mypico/cmake-arguments $ picotool load -f -x build/*.uf2Loading into RAM:     [==============================]  100%The device was rebooted to start the application.pi@Pi4B:~/mypico/cmake-arguments $ cat < /dev/ttyACM0Hello WorldHello World^C

Statistics: Posted by hippy — Sat Dec 13, 2025 2:54 pm



Viewing all articles
Browse latest Browse all 8013

Trending Articles