Including a dynamic build flag, without causing recompilation of everything every time?

Hi! I want to include the current git branch and commit hash as a string into my executable.

I’ve been playing with using an extra_scripts=pre: script to add it as a build flag, but this seems ot have unfortunate side effect of causing all objects to be recompiled every time, even if the file isn’t using this build flag. (I presume this is because build flags have changed and the compiler has no way of knowing if it would affect compilation of any of the files.)

Could anyone please point me to a way to achieve this?

I guess I could write the #define to a .h file at compilation, and keeping a ‘default unknown’ version of that .h file in git and added to .gitignore so that it won’t get added back to the repo every time, but wondering if there is a cleaner or more established way to pull this off :slight_smile:


1 Like

Generating a .h file instead of a flag seems clean to me. It will affect only the files that consume it.

BTW, with the dynamic flags, does the build compiles everything even if the build flag was not changed? If so, is it because the modify date of platformio.ini changed? In this case, can you not write to platformio.ini if the value was not changed?

Hi Zapta, just wanted to say thanks for the prompt on this. Your question made me go back and look at it again and implement the approach suggested.

The platformio.ini file wasn’t being changed in itself – it was the extra_scripts:pre script was adding to the environment build flags, and I think that’s what was causing unnecessary recompilation.

I ended up writing to a version.h file using this script:

And I used some arcane git commands I found on stackoverflow that make sure that changes to the include/version.h don’t get tracked, so I can change branches without worrying about the current branch+commit number ending up in the repository and confusing things :slight_smile:

1 Like