C style 'static' functions

John Burton via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 19 04:52:09 PDT 2017


On Wednesday, 19 July 2017 at 11:31:32 UTC, Jacob Carlborg wrote:
> On 2017-07-19 09:22, John Burton wrote:
>> In C I can declare a function 'static' and it's only visible 
>> from within that implementation file. So I can have a static 
>> function 'test' in code1.c and another non static function 
>> 'test' in utils.c and assuming a suitable prototype I can use 
>> 'test' in my program and the one in code1.c will not interfere.
>> 
>> In D it seems that declaring functions as static in a module 
>> does not affect visibility outside of a module. So if I 
>> declare a static function in one module with a specific name 
>> that is just used in internally for the implementation, and 
>> then define a function with the same name in another module 
>> that is intended to by 'exported' then in my main program they 
>> still conflict and I have to take steps to avoid this.
>> 
>> It looked as if I could use 'private' instead of static but 
>> although this prevents me from calling the "private" function, 
>> it still conflicts with the one I want to call.
>> 
>> In C++ I could use static or an anonymous namespace for 
>> implementation functions, but there doesn't seem to be 
>> anything similar in D.
>> Is there any way to achieve what I want in D (Private 
>> implementation functions)
>
> I think it would be easier if you provide a small code example 
> of what you want to achieve.


Here is an artificial example of what I mean. The point is that I 
can break main.d from compiling by adding what is meant to be a 
purely internal implementation detail inside  of lib1. - In C I 
can make internal functions static to avoid this... Im D, none of 
static, package, private etc seem to do this. They prevent it 
from being called but don't hide the existence of the function 
from the module importing it.

If there is no way to achieve this it's not a big problem, I'm 
just curious now :)


---- lib1.d ----

private void init()
{
     // init function used only as an implementation detail
}

void mything()
{
     init();
}


---- lib2.d -----

void init()
{
     // init function meant to be used as part of the module 
interface
}

---- main.d ----

import lib1;
import lib2;

void main()
{
     init();  // This is meant to call lib2.init because it's the 
only
              // function of that name. lib1.init() is supposed to 
be
              // an entirely internal implementation detail of lib1
              // Even though I can't call lib1.init() because it's 
private
              // this call still shows up as ambigous.
  	     //
              // In C I'd write "static void init()" in lib1.d to 
indicate
              // that the function was entirely local to that 
file. However static
              // does not appear to have that same effect in D
}




More information about the Digitalmars-d-learn mailing list