Code fails with linker error. Why?

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 4 04:09:33 PDT 2014


On Saturday, 4 October 2014 at 11:01:30 UTC, John Colvin wrote:
> On Saturday, 4 October 2014 at 10:38:32 UTC, ketmar via 
> Digitalmars-d-learn wrote:
>> On Sat, 04 Oct 2014 10:27:16 +0000
>> John Colvin via Digitalmars-d-learn 
>> <digitalmars-d-learn at puremagic.com>
>> wrote:
>>
>>> Sorry, but that's just not how it works. There is no 
>>> requirement for the definition of a function to be found in 
>>> the same compilation unit as it's declaration.
>> is there any possibility to declare *class* *method* in one 
>> file and to
>> implement it in another? O_O
>>
>> i doubt so.
>
> Yes, you can. You just have to get the mangling right.
>
> // methodLink.d
> class A
> {
>     void foo();
> }
>
> void main()
> {
>     auto a = new A;
>     a.foo();
> }
>
> // missingMethod.d
> import methodLink;
> import std.stdio;
>
> pragma(mangle, A.foo.mangleof)
> void foo() { writeln("Hello World"); }
>
> $ dmd missingMethod.d -c
> $ dmd methodLink.d missingMethod.o
> $ ./methodLink
> Hello World

Inheritance works too:

//methodLink.d
import std.stdio;
class Base
{
     void foo() { writeln("From Base"); }
}

class A : Base
{
     override void foo();
}

void main()
{
     Base a = new A;
     a.foo();

     a.Base.foo();
}

$ dmd methodLink.d missingMethod.o
$ ./methodLink
Hello World
 From Base


More information about the Digitalmars-d-learn mailing list