dmd icon indicating copy to clipboard operation
dmd copied to clipboard

[ImportC] Compilation fails when casting to struct defined in separate file

Open dlangBugzillaToGithub opened this issue 2 years ago • 3 comments

Lance Bachmeier (@bachmeil) reported this on 2024-03-11T02:44:55Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=24435

Description

structdef.c:

typedef struct {
	int a;
	double b;
} foo;

test.c:

#include <stdio.h>
#include <stdlib.h>

__import structdef;

int main() {
	int * x = (int *) malloc(2*sizeof(int));
	x[0] = 1;
	x[1] = 2;
	printf("%d
", x[0]);
	printf("%d
", x[1]);
	
	// Fails to compile because it's imported
	foo * y = (foo *) malloc(sizeof(foo));
}

Compile with DMD 2.108.0-beta.1:

test.c(13): Error: expression expected, not `)`
test.c(13): Error: found `malloc` when expecting `)`

If the definition of foo is moved into test.c, it compiles and runs. The error only occurs when foo is defined in a separate file.

dlangBugzillaToGithub avatar Mar 11 '24 02:03 dlangBugzillaToGithub

lance (@bachmeil) commented on 2024-03-26T14:48:25Z

This is a preprocessor problem with the typedef. The following works:

structdef.c

typedef struct foo_ {
        int a;
        double b;
} foo;

structtest.c

#include <stdio.h>
#include <stdlib.h>

__import structdef;

int main() {
        int * x = (int *) malloc(2*sizeof(int));
        x[0] = 1;
        x[1] = 2;
        printf("%d\n", x[0]);
        printf("%d\n", x[1]);

        // Works
        foo * y = (struct foo_ *) malloc(sizeof(foo));
        // Fails to compile because it's imported and typedef'd
        foo * y = (foo *) malloc(sizeof(foo));
}

dlangBugzillaToGithub avatar Mar 26 '24 14:03 dlangBugzillaToGithub

I believe this is a duplicate of https://github.com/dlang/dmd/issues/18094.

drpriver avatar Apr 15 '25 03:04 drpriver

Not sure if this is related, but I found a similar problem, but with an import from D:

file1.d:

module file1;

struct Foo {}

file2.c:

__import file1;

int main(void) {
    Foo* ptr = (Foo*)0;
}

The error results as:

file2.c(4): Error: expression expected, not `)`
    Foo* ptr = (Foo*)0;
                    ^
file2.c(4): Error: found `0` when expecting `)`
    Foo* ptr = (Foo*)0;
                     ^

Now, if you change to:

    Foo* ptr = (struct Foo*)0;

Then I don't get an error.

schveiguy avatar Nov 22 '25 19:11 schveiguy