How to pass variables to west

I want to pass a variable to my program so I'm using the command:
west build -b nrf52840dk_nrf52840 -p --build-dir build -- -Dmy_variable=40

Then in my program I want to print it:

int main()
{
  #ifdef my_variable
    printf("my_variable = %i",my_variable);
  #else
    printf("my_variable is not defined");
  #endif
}


But the result is "my_variable is not defined". What am I doing wrong?

Parents
  • Hi,

    The slightly more complex but more in the "Zephyr spirit", method would be to add a Kconfig file to your project defining it:

    config MY_VARIABLE
    int "My variable explain explain explain"
    range 10 100
    help
        This is an example for how to set a custom variable for your application
    
    menu "Zephyr Kernel"
    source "Kconfig.zephyr"
    endmenu
    

    And then use -DCONFIG_MY_VARIABLE.

    This will let you define it in prj.conf if you want as well.
    And you can take advantages of features of Kconfig, such as the range attribue I show in my example. (That can also be removed, it is optional).

    Regards,
    Sigurd Hellesvik

  • I tried it, but I could not get it to work.

    I created the file Kconfig.application in my project folder. When I compile I still get the cmake warning:

    CMake Warning:
    Manually-specified variables were not used by the project:

    MY_VARIABLE

    How does west find the Kconfig file? Do I need to add something to CMakeLists.txt? Do you have any references for documentation how to do this?

  • I'm not sure if Kconfig.application is the right naming for Kconfig files.
    So I renamed it to Kconfig.defconfig.
    Then I also added in CMakeLists.txt the following:

    set(ZEPHYR_EXTRA_KCONFIG_FILES ${CMAKE_CURRENT_SOURCE_DIR}/Kconfig.defconfig)


    When I print the variable in CMakeLists.txt, it gets the correct value:
    message("MY VARIABLE is: ${MY_VARIABLE}")


    But in main.c MY_VARIABLE is still undefined.

    This is my Kconfig.defconfig:

    config MY_VARIABLE
    string "my variable explain bla bla"
    default "default my variable"
    help
    This is an example for how to set a custom variable for your application

  • Have a look at our samples. They use a file named simply "Kconfig". Does that work for you?

Reply Children
Related