www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - DMD Stdio Linker Oddities

reply Jake Pittis <jakepittis gmail.com> writes:
I'm posting this in Learn because I'm assuming I've done 
something wrong rather than discovered a bug.

Running `dmd -main main.d` with the following 3 files produces 
the following linker error.

```
$ dmd -main main.d
Undefined symbols for architecture x86_64:
   "_D13linking_fails12__ModuleInfoZ", referenced from:
       _D4main12__ModuleInfoZ in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to 
see invocation)
Error: linker exited with status 1
```

```
// main.d
import linking_succeeds;
import linking_fails;
```

```
// linking_succeeds.d
import std.range;
```

```
// linking_fails.d
import std.stdio;
```

In the `linking_fails.d` file, if I replace the stdio import with 
`import std.algorithm`, running `dmd -main main.d` succeeds. 
Somehow stdio is causing the linker to fail.

Any idea what's going on or how to fix it? Thanks!

(DMD64 D Compiler v2.072.0, macOS Sierra 10.12)
Dec 24 2016
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Saturday, 24 December 2016 at 19:58:45 UTC, Jake Pittis wrote:
 I'm posting this in Learn because I'm assuming I've done 
 something wrong rather than discovered a bug.
You need to pass all modules you use to the linker somehow. Easiest is to `dmd main.d linking_succeeds.d linking_fails.d` just pass them all to dmd at once. Alternatively, you can compile all separately with `dmd -c` then you link them all with `dmd main.o linking_succeeds.o linking_fails.o` or put them in a lib etc.
 In the `linking_fails.d` file, if I replace the stdio import 
 with `import std.algorithm`, running `dmd -main main.d` 
 succeeds. Somehow stdio is causing the linker to fail.
You should pass all at once, but the reason why it sometimes works and sometimes doesn't is that std.stdio has a module constructor and algorithm doesn't. Since the module constructor is there, it becomes a load time dependency and requires the module info be present even with nothing else used.
Dec 24 2016