Explain the Modules to me but better...

Nemanja Boric via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Dec 29 11:00:25 PST 2016


On Thursday, 29 December 2016 at 18:20:22 UTC, Modules Confuse Me 
wrote:
> I'm trying to get going with D, but I keep getting hung up on 
> modules. I personally like having many smaller files. Generally 
> classes and interfaces all go into their own file. Even if the 
> overall file ends up being smaller than 10 lines of real code.
>
> After reading:
>
> https://dlang.org/spec/module.html
>
> I seem to have at least enough information to get things 
> working, but things break down after I start trying to package 
> everything up into packages. Because it's a pain in the butt to 
> have to include my interface files in separate imports than the 
> implemented classes. So, I see D has packages, but whenever I 
> use them I start getting errors like:
>
> Error: linker exited with status 180314872
>
> I'm really getting hung up on a simple thing, such as how to 
> structure my program in the 'D' way. So correct me if I am 
> wrong. In my packages, I should be using 'public' imports 
> correct? So that the imports get forwarded. I'm looking through 
> phobos, to try to get a good idea of how others do it, and I 
> don't see myself doing things too differently...

If you have following:

```
main.d

import a.mod;
import a.mod2;

void main() {
     foo();
     bar();
}
```

```
a/mod.d

module a.mod;

void foo() {}
```

```
a/mod2.d

module a.mod2;

void bar() {}
```

And you try to compile this with

```
dmd main.d
```

you will get the following error (depends on your system)

```
main.o: In function `_Dmain':
main.d:(.text._Dmain+0x5): undefined reference to 
`_D1a3mod3fooFZv'
main.d:(.text._Dmain+0xa): undefined reference to 
`_D1a4mod23barFZv'
collect2: error: ld returned 1 exit status
Error: linker exited with status 1
```

The reason for this is that dmd doesn't build any module except 
the ones in the command line (main.d in your case). So, when it 
tries to link, it will not find object files for foo and bar that 
are contained in the different module.

Solution could be to pass all files to dmd, so it will build them 
all:

```
dmd main.d a/mod.d a/mod2.d
```

or to use `rdmd` which will figure out which files needs 
building, so it will
do that for you manually:

```
rdmd main.d
```


More information about the Digitalmars-d-learn mailing list