When trying to emplace a struct with dmd -betterC, a linker reports a missing symbol. The program
import core.stdc.stdlib;
import std.conv;
struct TestStruct
{
int i;
}
extern (C)
int main(size_t argc, char** argv)
{
enum size = TestStruct.sizeof;
auto buf = malloc(size);
scope(exit) free(buf);
auto r = emplace!TestStruct(buf[0 .. size]);
return 0;
}
Leads to
betterc_2.o: In function `_D3std4conv__T7emplaceTS9betterc_210TestStructZQBhFNaNbNiAvZPQBm':
betterc_2.d:(.text._D3std4conv__T7emplaceTS9betterc_210TestStructZQBhFNaNbNiAvZPQBm[_D3std4conv__T7emplaceTS9betterc_210TestStructZQBhFNaNbNiAvZPQBm]+0x24): undefined reference to `_D3std4conv16testEmplaceChunkFNaNbNiNfAvmmZv'
Without -betterC it works just fine.
Comment #1 by chalucha — 2020-12-23T09:51:56Z
Similar problem when using core.lifetime:
```D
import core.lifetime;
import core.stdc.stdlib;
struct Foo { int bar; }
extern(C) void main()
{
auto pf = malloc(Foo.sizeof)[0..Foo.sizeof].emplace!Foo(42);
assert(pf.bar == 42);
}
```
With: dmd -g -debug -betterC -ofbc bc.d
Leads to:
/usr/bin/ld: bc.o: in function `_D4core8lifetime__T7emplaceTS2bc3FooTiZQuFNaNbNiAviZPQz':
/home/tomas/dlang/dmd-2.094.2/linux/bin64/../../src/druntime/import/core/lifetime.d:284: undefined reference to `_D4core8lifetime16testEmplaceChunkFNaNbNiNfAvmmZv'
Comment #2 by chalucha — 2020-12-23T09:54:00Z
For the record, this works (uses different template):
auto pf = (cast(Foo*)malloc(Foo.sizeof)).emplace!Foo(42);
Comment #3 by dlang-bot — 2021-04-27T14:49:32Z
@MoonlightSentinel created dlang/druntime pull request #3454 "Fix 19783 - Fail to emplace struct with betterC" fixing this issue:
- Fix 19783 - Fail to emplace struct with betterC
Defining the helper function as a template ensures that it is available
when not linking druntime.
(`pragma(inline, true)` didn't work)
https://github.com/dlang/druntime/pull/3454
Comment #4 by dlang-bot — 2021-04-29T06:25:06Z
dlang/druntime pull request #3454 "Fix 19783 - Fail to emplace struct with betterC" was merged into master:
- 41df5db46f613b5f538d51d53441fcfbe2760aab by MoonlightSentinel:
Fix 19783 - Fail to emplace struct with betterC
Defining the helper function as a template ensures that it is available
when not linking druntime.
(`pragma(inline, true)` didn't work)
https://github.com/dlang/druntime/pull/3454