Libraries

Let’s discuss libraries in this lesson.

We'll cover the following

A collection of compiled modules is called a library. Libraries are not programs themselves; they do not have the main() function. Libraries contain compiled definitions of functions, structs, classes, and other features of modules, which are to be linked later by the linker to produce the program.

We can use dmd’s -lib command line option to create libraries. The following command makes a library that contains the “cat.d” and the “dog.d” modules. The name of the library is specified with the -of switch:

$ dmd animal/cat.d animal/dog.d -lib -ofanimal -w -de

The actual name of the library file depends on the platform. For example, the extension of library files is .a under Linux systems: animal.a.

Once the library is built, it is no longer necessary to specify the “animal/cat.d” and “animal/dog.d” modules individually. The library file is sufficient:

$ dmd deneme.d animal.a -w -de

The command above replaces the following one:

$ dmd deneme.d animal/cat.d animal/dog.d -w -de

As an exception, the D standard library Phobos need not be specified on the command line. That library is automatically included behind the scenes. Otherwise, it could be specified similar to the line below:

$ dmd deneme.d animal.a /usr/lib64/libphobos2.a -w -de

Note: The name and location of the Phobos library may be different on different systems.

Using libraries of other languages

D can use libraries that are written in some other compiled languages like C and C++. However, because different languages use different linkages, such libraries are available to D code only through their D bindings.

Linkage is the set of rules that determines the accessibility of entities in a library as well as how the names (symbols) of those entities are represented in compiled code. The names in compiled code are different from the names that the programmer writes in source code; the compiled names are name-mangled according to the rules of a particular language or compiler.

For example, according to C linkage, the C function name foo would be mangled with a leading underscore as _foo in compiled code. Name-mangling is more complex in languages like C++ and D because these languages allow using the same name for different entities in different modules, structs, classes, etc., and for overloads of functions. A D function named foo in source code has to be mangled to differentiate it from all other foo names that can exist in a program. Although the exact mangled names are usually not important to the programmer, the core.demangle module can be used to mangle and demangle symbols:

Get hands-on with 1200+ tech skills courses.