www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Trying to call some C code using Extern(C) but got unexpected linker

reply Xiaochao Yan <leon_whbc yahoo.com> writes:
Hi, I am new to D and is experimenting with game development 
using D and C.

I had some problem when trying to recreate the
https://dlang.org/spec/importc.html

Environment:
Windows 11
gcc.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 8.1.0

Error Message:
```
lld-link: error: undefined symbol: _D4test4mainFZ12printMessageUZv
 referenced by test.obj:(_Dmain)
``` ``` // .c file #include <stdio.h> void printMessage() { printf("Hello from C!\n"); } ``` ``` // .d file import std.stdio; import std.conv; import test; void main() { writeln("Hello, World!"); extern (C) void printMessage(); printMessage(); } ``` Thanks in advance!
Jun 07
next sibling parent Steven Schveighoffer <schveiguy gmail.com> writes:
On Saturday, 8 June 2024 at 02:22:00 UTC, Xiaochao Yan wrote:
 Hi, I am new to D and is experimenting with game development 
 using D and C.

 I had some problem when trying to recreate the
 https://dlang.org/spec/importc.html

 Environment:
 Windows 11
 gcc.exe (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 
 8.1.0

 Error Message:
 ```
 lld-link: error: undefined symbol: 
 _D4test4mainFZ12printMessageUZv
 referenced by test.obj:(_Dmain)
``` ``` // .c file #include <stdio.h> void printMessage() { printf("Hello from C!\n"); } ``` ``` // .d file import std.stdio; import std.conv; import test; void main() { writeln("Hello, World!"); extern (C) void printMessage(); printMessage(); } ``` Thanks in advance!
Put `printMessage` outside the main function. Inside the main function, it has C linkage, but not C name mangling. -Steve
Jun 07
prev sibling parent Basile B. <b2.temp gmx.com> writes:
On Saturday, 8 June 2024 at 02:22:00 UTC, Xiaochao Yan wrote:
 Hi, I am new to D and is experimenting with game development 
 using D and C.

 I had some problem when trying to recreate the
 https://dlang.org/spec/importc.html

 [...]

 Thanks in advance!
on a recent compiler this should work: ```d // .d file import std.stdio; import std.conv; import test; void main() { writeln("Hello, World!"); pragma(mangle, "printMessage"); extern (C) void printMessage(); printMessage(); } ``` This was fixed by the dear GH Ghost in https://github.com/dlang/dmd/pull/15582. A short technical explanation: mangling and call conventions are not 100% related. You need to stuff the mangle for that to work.
Jun 08