Skip to main content
DSudo.2
Associate III
September 20, 2023
Solved

Read environment variable during build and pass value to file to be compiled

  • September 20, 2023
  • 1 reply
  • 2497 views

Is there a way to read an environment variable from the PC (I'm running on a Windows box) and pass that value somehow (maybe via a temporarily created define for the command line) such that a file being compiled can use the value of that environment variable? For example, can the name of the person who's doing the build be used to initialize a string value that can then be embedded into the app?

Thanks!

This topic has been closed for replies.
Best answer by TDK

Yes, but converting it to a string is awkward.

Add "USERNAME=$(USERNAME)" switch to your preprocessor defines.

Then, in your program:

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

...

printf("username=%s\n", TOSTRING(USERNAME));

 Might be a way to add the quotes in the define itself but I couldn't figure it out. The shell is fighting itself with expanding things.

1 reply

TDK
TDKBest answer
September 20, 2023

Yes, but converting it to a string is awkward.

Add "USERNAME=$(USERNAME)" switch to your preprocessor defines.

Then, in your program:

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)

...

printf("username=%s\n", TOSTRING(USERNAME));

 Might be a way to add the quotes in the define itself but I couldn't figure it out. The shell is fighting itself with expanding things.

"If you feel a post has answered your question, please click ""Accept as Solution""."
DSudo.2
DSudo.2Author
Associate III
September 20, 2023

Accepted as solution, but after further investigation https://gcc.gnu.org/onlinedocs/gcc-4.8.5/cpp/Stringification.html there is no way to convert a macro argument into a character constant, and gcc generates an error any way I try to convert USERNAME into something I can use as a const char*.

TDK
September 20, 2023

I tested it. It works for me. Win10 STM32CubeIDE.

What error are you getting?

"If you feel a post has answered your question, please click ""Accept as Solution""."