www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - extern(C) on var decl is confusing

reply user1234 <user1234 12.de> writes:
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.
Jul 27
next sibling parent Jonathan M Davis <newsgroup.d jmdavisprog.com> writes:
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
Jul 28
prev sibling parent reply kinke <noone nowhere.com> writes:
On Sunday, 27 July 2025 at 23:23:40 UTC, user1234 wrote:
 That is confusing
It affects the mangling of global vars, just like functions.
Jul 28
parent user1234 <user1234 12.de> writes:
On Monday, 28 July 2025 at 11:06:40 UTC, kinke wrote:
 On Sunday, 27 July 2025 at 23:23:40 UTC, user1234 wrote:
 That is confusing
It affects the mangling of global vars, just like functions.
ah indeed
Jul 28