Request assistance converting C's #ifndef to D

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 13 08:35:48 PDT 2016


On 5/13/16 12:59 AM, Andrew Edwards wrote:
> On 5/13/16 8:40 AM, Andrew Edwards wrote:
>>> That seems wrong. You can't assign to an enum. Besides, doesn't your
>>> declaration of MIN shadow whatever other definitions may be currently in
>>> effect?
>>
>> Okay, got it. It seams I just hadn't hit that bug yet because of other
>> unresolved issues.
>>
>>> Perhaps what you meant is something like this?
>>>
>>>     static if (!is(typeof(MIN) : int))
>>>         enum MIN = 99;
>>
>> This seems to do the trick.
>
> But not exactly the way it's expected to. In the snippets below, C
> outputs 10 while D outputs 100;
>
> min.c
> =========================
>      #define MIN 10 // [1]
>
>      #include "mild.h"
>
>      int main()
>      {
>              print();
>              return 0;
>      }
>
> min.h
> =========================
>      #include <stdio.h>
>
>      #ifndef MIN
>      #define MIN 100
>      #endif
>
>      void print()
>      {
>          printf("%d\n", MIN);
>      }
>
> minA.d
> =========================
>      enum MIN = 10; // [1]
>
>      import minB;
>
>      void main()
>      {
>          print();
>      }
>
> minB.d
> =========================
>      static if (!is(typeof(MIN) : int))
>          enum MIN = 100;
>
>      void print()
>      {
>              import std.stdio: writeln;
>              writeln(MIN);
>      }
>
> Is there a way to reproduce the same behavior? Are there reason's for
> not allowing this functionality or am I just misunderstanding and going
> about things the wrong way?

Code like this is FUBAR.

I have seen abuse of pre-processor in many places, and it never 
justifies the cleverness of how it is done.

Note that min.h is providing an inlined function. Essentially, min.h is 
like a template with the definition of the template parameter defined by 
the including file. But you can only ever include min.h ONCE in your 
entire project, or you will get linker errors.

D will always compile a module without external configuration. That is, 
print is compiled ONCE and only in the context that minA.d defines. 
Inlining can replace the print call with inline functions, but it will 
still be compiled according to the module's definitions, not external.

TL;DR: there isn't a good way to port this code, because it's shit code, 
and D doesn't do that :)

-Steve


More information about the Digitalmars-d-learn mailing list