Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Tooling and Interop

dub, Modules and Packages in D

Learn D modules and the dub build tool: module and import rules, package layout, dub.json and dub.sdl, dependencies, build types, and a C dependency-resolution stand-in.

Real programs are many files. D organizes code in modules (one per source file) and packages (directories of modules). dub is the standard build tool and package manager: it reads a recipe file, downloads dependencies from the package registry, calls the compiler and runs your tests. This lesson covers modules first, then dub.

Neither a D compiler nor dub runs on this site, so commands and files are shown read-only. The runnable stand-in is a C program that does what dub does first: resolve dependencies into a build order.

Modules and imports

Each .d file is a module. Its name comes from the optional module declaration, or from the file name:

D
// file: source/geometry/shapes.d
module geometry.shapes;

struct Rect { double w, h; double area() const { return w * h; } }

private double helper() { return 0; }   // only visible inside this module
D
// file: source/app.d
import std.stdio;
import geometry.shapes;                   // the whole module

void main()
{
    writeln(Rect(3, 4).area());
}

Import forms:

Form Meaning
import a.b; everything public from a.b
import a.b : x, y; only x and y (selective)
import a = a.b; rename the module (a.x)
import a.b : z = y; rename a symbol
public import a.b; re-export, so importers of this module also see a.b

Imports can be local: place import std.algorithm; inside a function and it is visible only there. Modules are not textual includes; the compiler reads each once, and circular imports between modules are allowed unless both define static constructors that depend on each other.

A directory with a package.d file defines a package module: import geometry; loads geometry/package.d, which usually does public import geometry.shapes; and friends.

Visibility attributes are public (default), private (module-level), package (this package and subpackages) and export (for shared libraries).

The standard project layout

Text
myapp/
  dub.json
  source/
    app.d
    geometry/
      package.d
      shapes.d
  views/        (optional string imports)

dub init myapp creates this skeleton. source/app.d containing main makes an executable; a library puts its public modules under source/ and has no main.

dub.json and dub.sdl

The recipe is either JSON or SDLang. The same project in JSON:

JSON
{
  "name": "myapp",
  "description": "Shape calculator",
  "authors": ["Your Name"],
  "license": "MIT",
  "targetType": "executable",
  "dependencies": {
    "mir-algorithm": "~>3.22.0"
  },
  "configurations": [
    { "name": "default" },
    { "name": "static", "targetType": "staticLibrary", "excludedSourceFiles": ["source/app.d"] }
  ]
}
  • targetType is executable, library, staticLibrary, dynamicLibrary or none.
  • A version ~>3.22.0 means "3.22.0 or newer patch releases, not 3.23". >=1.0.0 <2.0.0 and * are also valid.
  • dub.selections.json (created after the first resolve) pins exact versions: commit it for applications, not for libraries.
  • dflags, versions, libs, sourcePaths and importPaths tune compilation.

Everyday commands

Text
dub init myapp          # new project
dub build               # compile (debug by default)
dub run                 # build and run
dub test                # build with unittests and run them
dub build -b release    # optimized build (-O -release -inline)
dub add vibe-d          # add a dependency to the recipe
dub upgrade             # re-resolve to newest allowed versions
dub fetch some-package  # download a package
dub lint / dub describe # inspect

Build types are debug (checks on, symbols), release (optimized, contracts and bounds checks removed in -release, except safe code keeps bounds checks), unittest, profile, cov (coverage) and plain. The compilers behind dub are DMD (fast compile, reference), LDC (LLVM, best optimizer) and GDC (GCC). Choose one with --compiler=ldc2.

What dub does: dependency resolution

When you ask for a package, dub reads its recipe, finds its dependencies, picks a version for each that satisfies every constraint, and compiles dependencies before dependents. That order is a topological sort of the dependency graph, and a cycle is an error. The program below does that for a small graph. Each package lists the indexes of packages it needs.

C Stand-in: build order by topological sort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

core is built first and app last. Change one dependency so core depends on app to see the cycle report.

Version constraints in C

Version matching is another job dub performs. This second program checks ~> style compatibility on a version triple: ~>1.4.2 accepts 1.4.x with x >= 2, ~>1.4 accepts 1.y with y >= 4.

C Stand-in: does a version satisfy ~>?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Practical advice

  • Keep one public module per concept and re-export through package.d.
  • Use dub test in CI; put unittest blocks next to the code (see unit tests and contracts).
  • Pin dependencies with dub.selections.json for applications.
  • Use LDC for release builds and DMD for quick edit-compile cycles.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does import a.b : x; do?

    A colon introduces a selective import.
  2. 2. What does the dependency version ~>2.1.3 allow?

    ~> allows increases only in the last given component.
  3. 3. Which command builds with the unit tests enabled and runs them?

    dub test builds the unittest configuration and runs it.
  4. 4. What file makes import geometry; load several sub-modules?

    package.d defines the package module, typically with public import lines.

Summary

  • A file is a module; directories are packages; package.d forms the package module.
  • Selective, renamed and public imports control visibility.
  • dub.json or dub.sdl describe the project; dub build/run/test drive it.
  • Dependencies compile in topological order; versions use ~> and ranges.
  • DMD, LDC and GDC are the compilers behind dub.

Next: Unit Tests and Contracts