extern(C) and name mangling

Jacob Carlborg doob at me.com
Wed Dec 16 06:46:42 UTC 2020


On Wednesday, 16 December 2020 at 04:17:13 UTC, Mike Parker wrote:

> However, the D calling convention is defined to be identical to 
> the C calling convention on the host system for everything 
> except Windows x86.

That's what's specified, but that's not how DMD actually behaves. 
DMD passes the arguments in reverse order. That's easily 
observable by calling a C function with D linkage:

$ cat foo.c
#include <stdio.h>

void foo(int a, int b)
{
     printf("a=%d b=%d\n", a, b);
}

$ cat main.d
module main;

import std;

pragma(mangle, "foo") // override D mangling to get the same name 
as the C function
void foo(int a, int b); // D calling convention

void main()
{
     foo(1, 2);
}

$ clang -o foo.o foo.c -c
$ dmd main.d foo.o
$ ./main
a=2 b=1

LDC behaves the same way as DMD and, IIRC, GDC follows how GCC 
passes the arguments.

--
/Jacob Carlborg




More information about the Digitalmars-d-learn mailing list