www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is there a -Dmacro like option for D compilers?

reply Jeremy <jtbx disroot.org> writes:
Is there a way I can define a manifest constant from the compiler 
command-line, like the -Dmacro option for C compilers?
Mar 27 2023
parent reply ryuukk_ <ryuukk.dev gmail.com> writes:
On Monday, 27 March 2023 at 22:22:26 UTC, Jeremy wrote:
 Is there a way I can define a manifest constant from the 
 compiler command-line, like the -Dmacro option for C compilers?
You can do this way: ``` dmd -version=FEATURE_A ``` ```D import std.stdio; void main() { version(FEATURE_A) { writeln("feature A enabled"); } } ``` Unfortunatly there is not #ifndef, so in case you want to make sure FEATURE_A is not there you'll have to do: ```D import std.stdio; void main() { version(FEATURE_A) {} else { writeln("feature A not available"); } } ``` or ```D import std.stdio; version(FEATURE_A) { enum FEATURE_A_AVAILABLE = true; } else { enum FEATURE_A_AVAILABLE = false; } void main() { static if (!FEATURE_A_AVAILABLE) { writeln("feature A not available"); } } ``` For some reason they force us to be overly verbose Or it's possible to do it, but i don't know much more than this about ``-version`` (if you use ldc compiler, it's ``-d-version=``)
Mar 27 2023
parent ryuukk_ <ryuukk.dev gmail.com> writes:
I just remembered you can do something like this!


```
import std.stdio;

enum FEATURE_A_AVAILABLE()
{
     version(FEATURE_A) return true;
     else return false;
}

void main()
{
     static if (!FEATURE_A_AVAILABLE)
     {
         writeln("feature A not available");
     }

}
```

It's evaluated at compile time, so it's branchless!
Mar 27 2023