Zero-cost version-dependent function call at -O0.

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 25 09:31:52 PDT 2017


On Sunday, 25 June 2017 at 15:58:48 UTC, Johan Engelen wrote:
> [...]
> If version(X) is not defined,  there should be no call and no 
> extra code at -O0.
> [...]
>
> In C, you could do something like:
> ```
> #if X
>   void foo() {......}
> #else
>   #define foo()
> #endif
> ```
>
> How would you do this in D?

By requiring the compiler to inline the empty foo:

```
version (Foo)
{
     void foo()
     {
         import std.stdio;
         writeln("foo");
     }
} else {
     pragma(inline, true)
     void foo() {}
}

void main(string[] args)
{
     foo();
}
```

See [1] for full assembly, shortened output as follows:

```
void example.foo():
         ret

_Dmain:
         xor     eax, eax
         mov     qword ptr [rsp - 16], rdi
         mov     qword ptr [rsp - 8], rsi
         ret
```

As you can see, while the code for the function itself will still 
be emitted, since it's empty the inlining will result in no 
instructions as the result.

[1] https://godbolt.org/g/RLt6vN


More information about the Digitalmars-d-learn mailing list