www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - beginner's linking error

reply James Cranch <j.d.cranch sheffield.ac.uk> writes:
Hi all,

I've just installed gdc from Debian Stable (gdc (Debian 
6.3.0-18+deb9u1) 6.3.0 20170516), and have been having linker 
errors when using writeln.

A minimal nonworking example is as follows: I have a file 
library.d which contains the following:

| module library;
|
| import std.stdio;
|
| class Greeter(string s) {
|
|   this() { }
|
|   void say_hello() {
|     writeln("Hello ", s, "!");
|   }
| }

I also have a file executable.d which contains the following:

| module executable;
| import library;
|
| int main() {
|
|   alias G = Greeter!("James");
|   G a = new G();
|   a.say_hello();
|   return 0;
| }

An attempt to compile it looks as follows:

| $ gdc executable.d -o executable
| /tmp/cc4RjTlb.o:(.data.rel+0x10): undefined reference to 
`_D7library12__ModuleInfoZ'
| collect2: error: ld returned 1 exit status

If I remove the import std.stdio and the writeln command from 
library.d, then it all works, so I'm clearly not linking 
libraries right, but it's not clear to me what to do.
Jan 17 2019
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 17 January 2019 at 10:38:50 UTC, James Cranch wrote:
 An attempt to compile it looks as follows:

 | $ gdc executable.d -o executable
You need to pass all the modules you use to the compiler, or compile each one at a time and pass the resultant .o files to the linker together.
 | /tmp/cc4RjTlb.o:(.data.rel+0x10): undefined reference to 
 `_D7library12__ModuleInfoZ'
This just means the library module was missing from the final link. (if you remove the other call from it, it made the library do nothing and thus the compiler didn't even actually emit the call to it). But try just gdc executable.d -o executable library.d so both .d files are on the list. That's the easiest and fastest way to make ti work.
Jan 17 2019
parent James Cranch <j.d.cranch sheffield.ac.uk> writes:
On Thursday, 17 January 2019 at 12:38:55 UTC, Adam D. Ruppe wrote:

 You need to pass all the modules you use to the compiler, or 
 compile each one at a time and pass the resultant .o files to 
 the linker together.
Marvellous, thanks! (Okay, it was a naive beginner's question. But I can't help thinking that there's a bit of a hole in the documentation shaped around this.)
Jan 17 2019