Thread overview
Is there a -Dmacro like option for D compilers?
Mar 27, 2023
Jeremy
Mar 27, 2023
ryuukk_
Mar 27, 2023
ryuukk_
March 27, 2023

Is there a way I can define a manifest constant from the compiler command-line, like the -Dmacro option for C compilers?

March 27, 2023

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

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:


import std.stdio;

void main()
{

    version(FEATURE_A)
    {}
    else
    {
        writeln("feature A not available");
    }

}

or


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=)

March 27, 2023

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!