Bug 22031 – crt_constructor functions can't initialize immutable/const variables

Status
RESOLVED
Resolution
WORKSFORME
Severity
minor
Priority
P3
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2021-06-16T17:20:47Z
Last change time
2023-01-15T07:48:32Z
Keywords
betterC, pull
Assigned to
No Owner
Creator
mipri
See also
https://issues.dlang.org/show_bug.cgi?id=23535

Comments

Comment #0 by mipri — 2021-06-16T17:20:47Z
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
Comment #2 by bugzilla — 2023-01-15T07:48:32Z
This is now working in master