Modules

Jonathan Marler via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 24 07:43:03 PDT 2016


On Sunday, 24 July 2016 at 02:45:57 UTC, rikki cattermole wrote:
> On 24/07/2016 2:28 PM, Rufus Smith wrote:
>> NM, ignore. Seems it was something else going on. Although, if 
>> you know
>> how how dmd resolves this stuff exactly, it would be nice to 
>> know. Does
>> it just use the module names regardless of path or does the 
>> path where
>> the module is located have any play(assuming they are properly 
>> passed to
>> the compiler).
>
> My understanding is this:
>
> 1. For each file passed, use supplied module name
> 2. If an import is unknown look at each of the directories 
> passed via -I and find it based upon a/b/c.d for module a.b.c;
> 3. For each file passed, if an import is unknown try to guess 
> based upon paths
>
> Of course rdmd adds another level of behavior on top and is 
> mostly based upon the third one.
>
> If in doubt, try using dub. It can show you all this without 
> looking at code ;)

The thing I remember being confused about was that you had to use 
the -I option to specify what root level module directories you 
want to import from AND in the file that is being imported you 
have to explicitly put the module name at the top of the file. In 
both cases, the error message you get usually doesn't make it 
obvious what you've done wrong.  I think if you forget to put the 
module name at the top of the file you'll end up with a very 
generic message like "can't import module y".

Note that this only takes care of compilation, and doesn't 
include how to make sure linking works.  If you need more info on 
that let me know.

For your example:
foo
    bar
       x
    baz
       y
       baz.d(package)

If you had a module inside the y directory, you would need to 
include the root level path for the y package like this:

foo/bar/x> dmd main.d -I../baz

Then each module you want from y, should be imported explicitly 
like this:
import y.coollib;
import y.awesomeutil;

If you want to import multiple files from y using "import y;", 
then there needs to be a package.d file inside the y directory:

foo/baz/y/package.d:
public import y.coollib;
public import y.awesomeutil;

The library may or may not have a package.d file.  If it does 
not, then each module is probably meant to be imported 
independently.

Also if you really need to know what's going on, you can find the 
source code that finds imports in dmd here(I just happen to know 
this because I just made a PR modifying this code): 
https://github.com/dlang/dmd/blob/master/src/dmodule.d#L48

Hope this helps.  I do remember being confused about how all this 
worked a few years ago but now it all makes sense.  Not sure if 
this information is easy to find or not, if it's not, it should 
be added somewhere.


More information about the Digitalmars-d-learn mailing list