| |
| Posted by Jonathan M Davis in reply to Andy Valencia | PermalinkReply |
|
Jonathan M Davis
Posted in reply to Andy Valencia
| On Monday, March 11, 2024 9:56:24 AM MDT Andy Valencia via Digitalmars-d-learn wrote:
> Leveraging my knowledge of C, I assumed a "static" function would be hidden outside of its own source file. I can't find any statement about the semantics of a static function in the documentation, and in practice (ldc2 on Linux) it doesn't hide the function?
No, static does nothing of the sort in D. You can read the documentation here:
https://dlang.org/spec/attribute.html#static
But what exactly static means varies based on the context.
For module constructors and destructors, it means that that constructor or destructor runs once for the entire program, whereas otherwise, they would run once per thread.
For member functions (i.e. functions on structs or classes), it means that the function has no this reference. So, it's a function on the struct/class itself and not associated with an instance of the struct/class, whereas non-static member functions must be called on an instance of that struct or class.
For nested functions, it means that the function does not have access to variables inside the function that it's nested in (whereas a non-static member function has access the symbols in the function that it's declared in).
For member variables (that is, variables on a struct or class), it makes it so that there is only one instance of that variable for that struct or class per thread rather than one per instance of the struct or class.
For variables within a function, it makes it so that there is only one instance of that variable per thread (as opposed to the variable only existing for the duration of a specific function call).
For nested structs or classes, it means that they don't have access to their outer scope (generally either the function that they're declared in or the class or struct that they're declared in).
I'm probably missing some other uses of static, but those are the ones that come to mind at the moment.
Aside from module constructors and destructors, I can't think of any case off the top of my head where static does anything at module scope. So, putting static on a function at module scope (rather than within a struct or class) does nothing.
If you want to control the visibility of any symbol within a module, then you need to use the visibility attributes:
https://dlang.org/spec/attribute.html#visibility_attributes
And specifically, to make a symbol only be visible inside a module, you mark it with private.
- Jonathan M Davis
|