How to create a function declaration?

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Fri Jan 12 09:09:01 PST 2007


Marcio Faustino wrote:
> How can I create a function declaration only and provide its definition later?

You can't. Not in the same file, at least.[1]

> For example:
> 
> /******************************************************************************/
> extern (C) int print(char*);
> 
> extern (C) int print(char* s) {
>     return printf("%s", s);
> }
> 
> void main() {
>     print(cast(char*) "test\0");
> }
> /******************************************************************************/
> 
> The compiler says:
> «test.d(9): function test.print called with argument types:
>         (char*)
> matches both:
>         test.print(char*)
> and:
>         test.print(char*)»


> What am I doing wrong?

You're writing forward declarations. Seriously, D doesn't need them; 
forward references are allowed ;).

A function declaration without definition is for when you put the 
definition in a different file, not to put it later in the same file.
It's mostly useful to link to libraries designed to link to C, though 
Phobos also uses it in object.d to link to definitions in internal/object.d.
It *could* also be useful to link to closed-source D libraries, but I 
haven't seen any yet...



[1]: I just had an evil idea. Turns out it's technically possible.
You can declare extern(C) it with a different argument type, then both 
overloads will have the same name in the executable (no name mangling) 
and the linker will link them both to the same definition.
But I wouldn't use this for anything serious, and I wouldn't have been 
surprised if it hadn't worked at all due to a symbol conflict or something.


More information about the Digitalmars-d-learn mailing list