Version 2.079 of the DMD compiler has just been released with improvements to the -betterC flag. I just gave it a try, and the D code I linked into a C executable with some horrible linker hacking in 2016 now works without any linker hacking at all. There’s still some more stuff to test out when I get around to it, but, hey, here’s some progress:

For reminders, here’s the D code once again:

module count;

@nogc:
nothrow:

import core.atomic : atomicOp, atomicLoad;

extern(C)
{
        int count()
        {
                scope(exit) counter.addOne();
                return counter.getValue();
        }
}

private:

shared struct AtomicCounter(T)
{
        void addOne() pure
        {
                atomicOp!"+="(_v, 1);
        }

        int getValue() const pure
        {
                return atomicLoad(_v);
        }

        private:
        T _v;
}

unittest
{
        shared test_counter = AtomicCounter!int(42);
        assert (test_counter.getValue() == 42);
        test_counter.addOne();
        assert (test_counter.getValue() == 43);
}

shared counter = AtomicCounter!int(1);

And here’s the C code:

#include <stdio.h>

int count();  // From the D code

int main()
{
    int j;
    for (j = 0; j < 10; j++)
    {
        printf("%d\n", count());
    }
    return 0;
}

And here’s it all compiling and linking cleanly:


$ dmd --version
DMD64 D Compiler v2.079.0-1-gde1725830-dirty
Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved written by Walter Bright
$ ls
count.d  program.c
$ dmd -c -betterC count.d 
$ gcc count.o program.c -o program
$ ./program 
1
2
3
4
5
6
7
8
9
10

Nice! Thanks to all the contributors.