I have a DMD + Tango bundle on linux. Please give me the step by step information, how can I use an external library in D, for example zlib
. I have compiled zlib.
I have a file tree like this:
myzlib
├── include
│ ├── zconf.h
│ └── zlib.h
└── lib
└── libz.a
I've got the import tango.io.compress.ZlibStream;
call in my myfile.d
source.
And these are my questions:
- Do I need to copy these files to the
dmd/lib
directory? - Do I need to modify
dmd/bin/dmd.conf
file? - How should I call
dmd
compiler (dmd myfile.d -Llibz.a
) or something else (maybe, with absolute paths)?
I've never tried to use external libraries in any other language. Please help me.
The
-L
flag tells the linker to add a particular directory to its search path.-l
tells it to link in a particular library, and it searches on its search path to find that library.With DMD, you have to pass flags to the linker with the
-L
flag. It can take either absolute or relative paths, but the paths need to be relative to where the compiler is run from. So if you use relative paths, then you always have to run the compiler from the same directory (which generally isn't a problem, since you'd typically have the build command in aMakefile
which you always run from the same directory).The most common thing is to use absolute paths for libraries installed on the system and relative paths for libraries specific to your project.
So, if you have the library
myzlib/lib/libz.a
, you would pass-L-Lmyzlib/lib -L-lz
todmd
.It would then add
myzlib/lib
to the linker's search path, and then look forlibz.a
in its search path (the linker knows to take the part following-l
, add lib to the front of it and add.a
suffix to the end to get the library that you're looking for).You can add the linker flags to
dmd.conf
, but I really wouldn't advise it. The flags indmd.conf
are what dmd always uses for every program. So, you should really only have the flags there that are used in all of your programs.Rather, feed them to dmd directly (be it on the command line or as part of a
Makefile
).As for the header files, you're going to need to duplicate any of their declarations that you need in a
.d
file.Header files are used by the C or C++ compiler, not the linker. D shares the same linker as you'd use for C or C++, but its compiler is
dmd
, notgcc
.So, you need to duplicate the C declarations in a D file. The simplest way to do that is with
htod
utility, but it only works in Windows or Wine.Regardless, you'll need to declare the C declarations that you'd be using in a
.d
file and mark them withextern(C)
.