extern(C) on var decl is confusing
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Jul 28 07:39:53 UTC 2025
On Sunday, July 27, 2025 5:23:40 PM Mountain Daylight Time user1234 via Digitalmars-d-learn wrote:
> That is confusing, e.g
>
> ```
> extern(C) int r;
>
> int main()
> {
> return r;
> }
> ```
>
> works. But what is likely more intended here is
>
> ```
> extern int r;
>
> int main()
> {
> return r;
> }
> ```
>
> which leads, this time, to the expected linker error.
For better or worse, it's pretty common for the compiler to ignore
attributes which can't apply to a particular symbol. And a lot of it comes
down to stuff like the ability to mass-apply attributes, e.g.
extern(C):
is a common thing to do with C bindings, and the compiler pretty much needs
to ignore extern(C) on anything that extern(C) can't apply to, or extern(C):
isn't going to work very well. And it doesn't just come up with variables.
static can affect a variety of symbols, but it gets ignored in some cases as
well if it's mass-applied even with symbols that aren't variables.
Invalid attributes are also allowed in some cases, because it works better
that way for generic code, e.g.
scope T var;
doesn't have to worry about whether T is a type where scope has any real
meaning.
So, in some respects, ignoring attributes that can't apply simplifies
things, but of course, there are also situations where it causes confusion.
And maybe the compiler should make more of those cases errors than it
currently does, but it would likely be worse overall to make them all
errors.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list