How to set constant value to environment variable at compile time?

aliak something at something.com
Mon Dec 10 17:58:32 UTC 2018


On Monday, 10 December 2018 at 11:08:23 UTC, Narxa wrote:
> Hello, people!
>
> I would like to have a constant with the value of some 
> environment variable that is defined at compile time.
>
> In FreePascal, it can be done by defining it in source as:
>
> VALUE_OF_SOMETHING = {$I %SOMETHING%};
>
> And I can call the compiler with (bash):
>
> SOMETHING='Anything' export SOMETHING; <compiler> <flags>
>
> And it will automatically assign VALUE_OF_SOMETHING to 
> 'Anything'.
>
>
> In GCC C compiler, the solution I found was more complicated 
> but it worked.
>
> I had to explicitly define the environment variable when 
> calling the compiler with:
>
> gcc <flags> -DSOMETHING=\""Anything"\" -o <output> <source_file>
>
>
> Now, I would like to do that with the 'dmd' compiler.
>
> I know I could possibly use 'gdc' to achieve that but I want to 
> use the 'dmd' compiler.
>
> Is it possible to do that such a thing or through source or any 
> other means?
>
>
> Thank you!

I don't know if it's possible but one way to do it would be to 
use the -J switch and give it a config file that has contents:

VAR1=Value1
VAR2=Value2

And then in source code:

immutable config = import("config");
mixin(parseConfig);

string parseConfig(string str) {
   string ret;
   foreach (line; str.split("\n")) {
     auto parts = line.split("=");
     ret ~= `string ` ~ parts[0] ~ ` = "` parts[2] `";`;
   }
   return ret;
}

You can also echo out the config file with bash or something

Cheers,
- Ali



More information about the Digitalmars-d-learn mailing list