This file named imminit.d:
immutable int example;
version(D_BetterC) {
pragma(crt_constructor) extern(C) void initialize() {
example = 1;
}
} else {
shared static this() {
example = 1;
}
}
Compiles fine without -betterC:
$ dmd -c imminit.d
$
And fails with it:
$ dmd -betterC -c imminit.d
imminit.d(5): Error: cannot modify `immutable` expression `example`
As https://dlang.org/spec/pragma.html#crtctor states that these functions are intended as "a simple replacement for shared static this in betterC mode.", it seems like they should have similar capabilities.
Comment #1 by dlang-bot — 2022-03-03T18:31:11Z
@MoonlightSentinel created dlang/dmd pull request #13751 "Fix 22031 - Allow modification of non-mutable in `crt_[con|de]structor`'s" fixing this issue:
- Fix 22031 - Allow modification of non-mutable in `crt_[con|de]structor`'s
Allow functions marked as `pragma(crt_[con|de]structor)` to modify
`const` / `immutable` variables, which is currently restricted to
module ctors / dtors. This enables the use of lazily initialized global
constants for applications without druntime.
Such function may not be called at runtime because they might violate
the guarantees of `const` / `immutable`. Hence it is now an error to
call a function marked as `pragma(crt_[con|de]structor)`.
https://github.com/dlang/dmd/pull/13751