Import modules into D

I am trying to use a base module importing into D (language version 2). As a guide, I used an example on dlang.org, but my simple program will not compile. Files are in the same directory.

Here is my main.d file:

import std.stdio; import mymodule; void main(string[] args){ sayHello(); writeln("Executing Main"); } 

And here is my module file content (mymodule.d):

 void sayHello(){ writeln("hello"); } 

For compilation, I run through bash:

 dmd main.d 

And the error output:

 main.o: In function `_Dmain': main.d:(.text._Dmain+0x5): undefined reference to `_D8mymodule8sayHelloFZv' collect2: ld returned 1 exit status --- errorlevel 1 
+7
source share
2 answers
  • You need to specify all the modules that you compile on the command line. If you do not list the module, it will not be compiled. Modules that are compiled will be able to use uncompiled modules because the compiler retrieves its declarations, but the compiler does not create any object files for them. So, when the linker follows the link, he will complain that there are no definitions. In this case, he complains that mymodule.sayHello is undefined.

    If you want the compiler to automatically search for all the modules that the first module imports and compiles everything for you, you will need to use rdmd, which is a wrapper for dmd that comes with dmd, dmd itself does not. It only compiles the modules you are talking about.

  • You have not imported std.stdio to mymodule. Thus, even if you execute dmd main.d mymodule.d as you should be (or even better, dmd -w main.d mymodule.d or dmd -wi main.d mymodule.d ), it will not be able to compile mymodule because writeln not been declared. The fact that main.d imported it does not affect mymodule.

  • Although you have nothing to do in this case, you really need to place the module modulename; at the top of your modules. The compiler will output the module name from the file name, but after you have subpackages, you need to do this or you will have problems with import, because only the file name is called, not the package names. So, if you have foo/bar/mod.d and you do not have a module declaration in mod.d , it will be output as mod , not foo.bar.mod .

+10
source

dmd mymodule.d main.d

I know only those languages ​​that are smart enough for self-development of dependencies: Go and Haskell.

+4
source

All Articles