1.25. Causing a Source File to Be Linked Automatically Against a Specified Library
Problem
You’ve written a library that you’d like to distribute as a collection of headers and prebuilt static or dynamic libraries, but you don’t want users of your library to have to specify the names of the binaries when they link their applications.
Solution
If you are programming for Windows and using the Visual C++, Intel, Metrowerks,
Borland, or Digital Mars toolsets, you can use pragma
comment in your library’s headers to specify the names,
and optionally the full file pathnames, of the prebuilt binaries against which any code
that includes the headers should be linked.
For example, suppose you want to distribute the library from Example 1-1 as a static library libjohnpaul.lib together with the header johnpaul.hpp. Modify the header as shown in Example 1-26.
Example 1-26. Using pragma comment
#ifndef JOHNPAUL_HPP_INCLUDED #define JOHNPAUL_HPP_INCLUDED #pragma comment(lib, "libjohnpaul") void johnpaul(); #endif // JOHNPAUL_HPP_INCLUDED
With this change, the Visual C++, Intel, Metrowerks, Borland, and Digital Mars linkers will automatically search for the library libjohnpaul.lib when linking code that includes the header johnpaul.hpp.
Discussion
In some ways, linking can be a more difficult phase of the build process than compiling. One of the most common problems during linking occurs when the linker finds the wrong version of a library. This is a particular problem on Windows, where runtime libraries—and ...