How to import modules?
Mike Parker
aldacron at gmail.com
Mon Dec 3 23:17:09 PST 2012
On Tuesday, 4 December 2012 at 04:31:40 UTC, js.mdnq wrote:
> I created a .d file having a class with the modules tag at the
> top and everything public. I put it in a dir and used the -I
> flag
> to include the path. When I import the file I get an undefined
> method.
>
> 1. Do I need to compile the .d file into a lib or can I just
> import the .d and have it included directly. This is easier so I
> don't have to recompile when switching compilers.(to gdc)
The import statement simply tells the compiler which symbols are
visible. The compiler will not compile imported modules for you.
Given module foo.d, which imports bar.d, your command line should
look like this:
dmd -I/path/to/bar bar.d foo.d
Imports tell the compiler which symbols are available, but the
compiler will not automatically compile imported modules. You'll
have to do one of four things:
1) specify each source module on the command line so that each
can be compiled and linked
2) compile each source module individually and then manually link
the object files yourself
3) compile the imported files into a library and link with it
4) use a build tool like rdmd which parses all the imports makes
sure they are all compiled.
The only time it's possible to import a module without linking it
is when it is full of compile time symbols, such as templates
that are declared there but never instantiated, manifest
constants, etc...
>
> 2. Do I have to mark anything extern in the module?
No.
>
>
> In C/C++ one can just include the header, which contains code
> and
> it will work. In D, it seems like one has to link in the methods
> regardless? (at least when using the `imports <filename>`)
When the C or C++ source is in the header, this works because the
preprocessor directly merges the content of the header with the
source file that includes it. When the source is in a separate
file and only the interface is in the header, the source files
need to be compiled and linked. D compilers do not perform any
sort of substitution or merging like the C preprocessor. Each
module is compiled into an object file, just as C or C++ source
files are, and each must be linked into the executable.
>
> What I'm looking for is to get D to include the module using the
> D file directly unless it exists in a lib file. (or at least
> compile to a lib file and include it behind the scenes)
No D compiler does this. But rdmd, which ships with dmd, does.
>
>
>
> I'm also using dot notation.
>
> module/import MyModules.ThisModule; then the path looks like
> \Imports\MyModules\ThisModule.d. Not sure if this is the correct
> way to organize modules or not.
That is correct, though the prevailing convention is to use
lowercase module names.
More information about the Digitalmars-d-learn
mailing list