Very very noobie question about how imports work.

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 11 01:24:50 PST 2015


On Friday, 11 December 2015 at 03:51:35 UTC, tcak wrote:

> In D, directory structure doesn't matter. What matters is 
> module names.

Actually, it does matter sometimes.

// src/foo/bar.d
module foo.oops;

// main.d
import foo.oops;
void main() {}

Compile:
dmd -Isrc main.d

Result:
main.d(1): Error: module oops is in file 'foo\oops.d' which 
cannot be read

Compiling them together works:

dmd main.d src/foo/bar.d

When you pass multiple source modules on the command line, the 
compiler will determine the name of each module. If there is no 
module statement, it is the file name (but without the path -- 
it's in the default package). Otherwise, it's whatever is 
specified by the module statement. This name will be added to the 
list of available modules.

When compilation begins, each import statement is checked against 
the list of available modules. If the imported module is not 
found, the compiler will look for it on the import path. It will 
convert the fully qualified name of the imported module into a 
file path.

In the first command line above, when bar.d is not passed along, 
the compiler finds import foo.oops and searches the import path 
for foo/oops.d. Since that file does not exist, we get the error. 
Change the module statement in bar.d to 'module foo.bar' and the 
compiler will find it, since the src directory is added to the 
import path with -I.

In the second case, when foo.bar.d is passed to the command line, 
the compiler finds its module statement, 'module foo.oops' and 
adds 'foo.oops' to the list of available modules. In this case, 
the file name is irrelevant and compilation succeeds.

>
> Because it is logical to match directory structure and module 
> name, it is done in that way mostly, but there are times you 
> might not want this.

Module names should *always* match the file path unless you have 
a very compelling reason not to do so. As shown above, it's not 
just because it's logical, but because compilation can break when 
modules are compiled separately.


More information about the Digitalmars-d-learn mailing list