Using the GCC linker (static, dynamic linking)

From Elvanör's Technical Wiki
Jump to navigationJump to search

This article explains how the gcc linker can be used to link libraries in an executable, either statically or dynamically.

Command line options

Any option passed to the linker from gcc must use the syntax -Wl,<option>. By default, gcc seems to link dynamically, eg against the .so files on Linux (.dylib on Mac OS X, .dll on Windows). To prevent dynamic linking, pass the -static option to the linker. It will then try to link statically, using the .a versions of the libraries.

Note that in both cases, it will search for the libraries on some directories, usually specified by the Makefile (these directories appear on the command-line arguments given to the linker, they follow the -L flag). The name of the libraries themselves is given by the -l flag, for example -lmath.

The -lexample option tells the linker to search for a library of the name libexample.a.

Important information

Even when you think you are linking statically, you may in fact have dependencies. This can happen when the .a libraries just reference the dynamic libraries. For example, Qt on Windows seem to built like that: even the .a libraries are present, they say to use the functions on the .dlls. You need to rebuild Qt statically in order to get .a libraries that contain the functions.

In fact, even when linking dynamically, apparently the .a files are needed, since they list which functions are present in the dynamic versions.

Useful Links