really why module declarations?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 26 18:52:00 PDT 2017


On Sunday, March 26, 2017 20:51:01 XavierAP via Digitalmars-d-learn wrote:
> I've perused both the spec[1] and Andrei's book, and I the idea I
> get is that module declarations are optional, recommended only in
> case of file names not being valid D names. But in the community
> (and Phobos) I see it's strongly recommended and used throughout.
>
> What's the reason? If the declaration overrides the path
> (provided the file is found) rather than enforcing path
> consistency by outputting a compile error, then what's the
> benefit of module declarations, if we have to be disciplined to
> keep it consistent with paths anyway?
>
> I'm busy starting my first big multi file D project, thanks for
> any feedback!
>
>
> [1] https://dlang.org/spec/module.html#ModuleDeclaration

What it really comes down to is that if you don't give the module name, the
compiler infers it, and it doesn't infer packages. So, if you have

foo/bar.d

where bar.d's contents are

==========================================
void main()
{
    pragma(msg, __MODULE__);
}
==========================================

and you compile with dmd foo/bar.d, you're going to see

bar

printed, whereas if you have

==========================================
module foo.bar

void main()
{
    pragma(msg, __MODULE__);
}
==========================================

then you'll see

foo.bar

printed. So, if all you're ever doing is one file programs, then it really
doesn't matter, but if you're doing anything with packages, you have to use
module declarations. You also have to use them if you want to document a
module.

As for "overiding" the path... the compiler and other tools use the module
path as the path on disk to look for the files - e.g. if you tell the
compiler that /usr/local/include/dlang/ is an import directory, it'll start
looking for modules in there, and if it's looking for foo.bar, that means
that it's looking for /usr/local/include/dlang/foo/bar.d. On some level, it
is possible to give a module name or package name that doesn't match the
exact file or folder names on disk, but really, that's just asking for
trouble. It'll work in some basic cases, but it'll fall flat on its face in
real projects.

rdmd goes a step further and will compile additional modules based on what's
imported (i.e. if a module is imported but wasn't previously compiled, it'll
compile it), and when a tool does something like that, it makes it that much
worse if your module path isn't equivalent to the path on disk.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list