The DLL Import Library Tool

In order to create DLLs, or to use DLLs provided by other programmers, you generally need to create import libraries. Import libraries look like ordinary libraries, but they contain special object files with the information required to perform dynamic linking at run-time. Import libraries are created using a definition or .def file. The tool for doing this with the GNU compiler suite is called dlltool.

To use dlltool to create an import library from a given .def file you can do something like this:

dlltool --dllname foo.dll --def foo.def --output-lib libfoo.a

That command generates an import library called libfoo.a from the definition file foo.def. The --dllname option tells dlltool to associate the library with a DLL that will be called foo.dll. The name included after in the --dllname option is the one that will be used by Windows to search for the DLL when your program is loaded. It should simply be the name of the DLL, without any directory name or path information.

PASCAL/STDCALL/WINAPI Functions

The STDCALL calling convention for functions is widely used in Win32 API functions (WINAPI and PASCAL are both synonyms for STDCALL). Internally gcc uses a special notation for such functions which includes an at mark (@) and a number at the end of the function name. However, most DLLs export the function names in plain form (without the @). In such a case the .def file should contain the complete names, with an @, and you have to supply the -k option to dlltool to tell it to remove (or kill) the @ extension from the names used by Windows when connecting the program which uses the import library to the DLL (the @ extension is still present inside the import library so that gcc, which uses the @ extensions, can find the correct symbols in the import library).

dlltool --dllname foo.dll --def foo.def --output-lib libfoo.a -k

Creating .def Files from DLLs

Sometimes you will have a DLL you want to use but no .def or import library. dlltool is not the right tool to use for this problem. Instead you should use impdef, which is not part of the GNU compiler suite, to extract the exported function names from the DLL and create a .def file. This is an unreliable process, but it is only generally necessary if you are using a DLL which is not open-source software. (And you'd never do that unless you absolutely had to, right?)

Here's how you use impdef:

impdef foobar.dll >foobar.def

That outputs the exported function names in the DLL foobar.dll and puts them in a .def file called foobar.def. If all goes well you can then use the .def file to produce an import library like this:

dlltool --dllname foobar.dll --def foobar.def --output-lib libfoobar.a

However, if the DLL uses STDCALL functions (see above) you will have to edit the .def file and add the correct @ extensions.

For more on DLLs and these topics see the section on DLLs in the main tutorial.