Search code examples
ddmd

dmd linker (OPTLINK) gives Error 42: Symbol Undefined when using extern


Linking the following two files gives me a link-error:

a.d:

import std.stdio;

extern string test ();

void main() {
    writeln(test());
    readln();
}

b.d:

string test () {
    return "hello";
}

the error I get is:

Error 42: Symbol Undefined _D1a4testFZAya`

---errorlevel 1

What is wrong ?

_________________________________________________

Edit: this is the right way to do it:

a.d:

import std.stdio;
import b;

void main() {
   writeln("some_var from Module b: \"", b.some_var, "\"");
}

b.d:

public string some_var = "Hello, world!";

//you can also use static module constructors to set your vars
static this() {
   some_var ~= " -- How are you?";
}

That code was kindly provided by Joshua Reusch in the excellent D forum for beginners in the digitalmars.com site.


Solution

  • Modify your a.d to:

    import std.stdio;
    import b;
    
    //extern string test ();
    
    void main() {
      writeln(test());
      readln();
    }
    

    extern is a linkage attribute and is mostly used to specify what calling convention to use for the given function (typically a C function in some library). More about extern and other attributes here: http://www.d-programming-language.org/attribute.html . If all you have are D source files, there is really no need for extern. However, if you mix C or C++ and D code, you will definitely have to use it.