| Topics: | Language and Phobos -DGui (example placeholder - can be any library) | ||
| Previous | Lessons: | 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -T | Next |
In this lesson, you will gain an understanding of D's module system.A module is a unit of code that contains definitions for variables, functions, and other D constructs thatbelong together. This is useful for creating reusable code. You've seen modules in every single lesson. In fact, all D source files are modules. Thestdio module contains functions likewriteln. The modulestdio is written in a file called stdio.d atdmd/src/phobos/std/stdio.d. It contains code that is useful for console input and output and file input and output. It is within apackage calledstd, which also contains modules such asstd.algorithm orstd.string, which you will learn about later. The Phobos library is just a big collection of modules that comes with a D compiler.
// main.dmodulemain;importstd.stdio;importmodule1;importbyebye:sayBye;voidmain(){happy();writeln("Mothers Day!");sayBye();// sayByeInItalian(); undefined identifier 'sayByeInItalian'}
// happy.dmodulemodule1;importstd.stdio;voidhappy(){write("Happy ");}privatevoidsad(){write("Who gives a darn about ");}private:voidmad(){}voidbad(){}
//bye.dmodulebyebye;importstd.stdio;voidsayBye(){writeln("Goodbye!");}voidsayByeInItalian(){writeln("Arrivederci");}
Compile like this:dmd main.d happy.d bye.d
All D code is inside modules. In D programs, there has to be one module with amain function. If one module imports another module, the imported module's definitions becomes available to the first module. In the introductory code, themain module imported two other modules:module1 andbyebye. However, whenbyebye was imported, only one function was imported: the sayBye function. The syntax for that isimport modulename : identifier1, identifier2, identifier3;.
D source files can specify the name of the module and what package it belongs to with amodule declaration, which goes at the beginning. For example, in thestdio module, there is this line:
modulestd.stdio;
That line specifies the name of the module (stdio) and the package it is located in (std). Each source file can only have a maximum of one module declaration. If there is none, the source file name (without the extension) becomes the module name.
Before thevoid in the definition ofsad inmodule1, you see the modifierprivate. That means that thesad function cannot be imported. You wouldn't be able to doimport module1 : sad, either.If you see a line that saysprivate:, everything below that line isprivate. Likewise, if you seeprivate { }, everything inside the curly brackets is private.
public modifier, which is the opposite of theprivate modifier. Declarations marked by neitherpublic norprivate arepublic by default.