Define macro at compile time

Hi, for my project I need to populate a macro with a random value for identification purposes. I used to do this with a python script and a flag with g++ like so:
$ g++ -D__RANDOM__="$(python random.py)" main.cpp -o main

I wanted to do this with mbed. I know you can specify a build profile with flags, but these only allow plain text. Does anyone know of a way to do this or something similar in mbed? I would like to keep the python script because the random value has some specific requirements.

Thank you for your time!

One way to do this is using a cmake buildscript with mbed-cmake:

string(RANDOM LENGTH 8 ALPHABET "0123456789" IDENTIFIER_VAL)
target_compile_definitions(your_app __RANDOM__=${IDENTIFIER_VAL})

The length and content of the random string are configurable, the docs are here. Note that using the snippet above will regenerate the random value each time CMake is run, not every single build. If you need to regenerate the random value each build, then you can use a custom target that runs a script which generates a header file containing the random value, and then have your program include the header file. The custom target will get remade each time you run make, so the value will change each build.

2 Likes