Translating C macros to D

Cym13 via Digitalmars-d digitalmars-d at puremagic.com
Tue Jul 11 08:11:59 PDT 2017


On Tuesday, 11 July 2017 at 06:51:33 UTC, Jacob Carlborg wrote:
> On 2017-07-11 03:31, Cym13 wrote:
>
>> Is not getting rid of the macro an option? By that I mean 
>> translating the code inside the macro (which can admitedly be 
>> hard because it doesn't have to be semanticaly correct code 
>> due to concatenations but most macros aren't so evil) and add 
>> a pass of cpp to the build.
>
> Not sure I fully understand. Could you give a concrete example? 
> BTW, it might not be possible if the macros are part of the API 
> and we want to keep the D API as close as possible to the C API.
>
>> Of course nobody wants to use the C preprocessor on D code, 
>> but it would work and I'd prefer ugly code that works and can 
>> be refactored than no working translation at all personnaly.
>
> Are you saying the D code could contain C preprocessor code?

Yeah, the C preprocessor (cpp) is a separate program from the 
compiler, you can use it independently as you would any template 
language. It does however prepends some infos that you'd have to 
strip out.

Example:

$ cat test.d
#define MAX(a, b) (a > b ? a : b)

void main(string[] args) {
     import std.stdio;

     int x = 13;
     int y = 42;

     writefln("The max of %d and %d is %d", x, y, MAX(x, y));
}

$ cpp test.d
# 1 "test.d"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "test.d"


void main(string[] args) {
     import std.stdio;

     int x = 13;
     int y = 42;

     writefln("The max of %d and %d is %d", x, y, (x > y ? x : y));
}



More information about the Digitalmars-d mailing list