Function prototype + definition in the same file
Steven Schveighoffer
schveiguy at yahoo.com
Tue Sep 25 09:52:02 PDT 2012
On Tue, 25 Sep 2012 10:40:41 -0400, Manu <turkeyman at gmail.com> wrote:
> On 25 September 2012 17:25, Steven Schveighoffer
> <schveiguy at yahoo.com>wrote:
>
>> On Tue, 25 Sep 2012 07:53:17 -0400, Manu <turkeyman at gmail.com> wrote:
>>
>> So I have this recurring pattern, it's really starting to annoy me.
>>> It stems from the fact that a function prototype and the definition can
>>> not
>>> appear in the same file in D (as it can in C/C++)
>>>
>>
>> Doing this is not illegal.
>>
>>
>> Eg,
>>>
>>> void func(int x); // <-- declaration of function, informs type and
>>> associated names, args, ...
>>>
>>> //later
>>> void func(int x) // <-- may be generated with magic (and may use the
>>> prototype declaration for type information as declared by the prototype
>>> above)
>>> {
>>> ... do stuff
>>> }
>>>
>>
>> This compiles. Do you have a better case to show the problem?
>>
>
> void blah();
>
> void blah()
> {
> int x = 0;
> }
>
> void f()
> {
> blah(); // <- call it
> }
>
>
> W:\project\main\sourcedata\plugins\remedy\modules\test_module.d(38):Error:
> function remedy.testmodule.blah called with argument types:
> (())
> matches both:
> remedy.testmodule.blah()
> and:
> remedy.testmodule.blah()
Oh, that is funny. I simply compiled the functions and didn't call them,
assuming if that compiled it was legal.
This is definitely a bug. In fact you can implement a function *twice*
and this isn't an error.
Check this out:
testme2.d:
module testme2;
import std.stdio;
void foo()
{
writeln("first");
}
void foo()
{
writeln("second");
}
testme2.di:
module testme2;
void foo();
testme.d:
import testme2;
void main()
{
foo();
}
Compile like this:
dmd -c testme2.d
dmd testme.d testme2.o
links, and when I run, it displays:
first
So clearly there isn't something right here, that should definitely be an
error.
I think there are two errors here. First, the spec does not say you
cannot prototype a function before declaring it. All it says is:
Functions without bodies:
int foo();
that are not declared as abstract are expected to have their
implementations elsewhere, and that implementation will be provided at the
link step. This enables an implementation of a function to be completely
hidden from the user of it, and the implementation may be in another
language such as C, assembler, etc.
from: http://dlang.org/function.html
I don't see any rules that would preclude pre-declaring a prototype, even
if it's not promoted to do this (after all, forward references should
always work, right?).
Second, you should not be able to compile two identically prototyped
functions with bodies into an object file, I have no idea how that even
works.
-Steve
More information about the Digitalmars-d
mailing list