cancel
Showing results for 
Search instead for 
Did you mean: 

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

DSudo.2
Associate II

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!

1 ACCEPTED SOLUTION

Accepted Solutions
TDK
Guru

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".

View solution in original post

3 REPLIES 3
TDK
Guru

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".

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*.

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".