When linking with external libraries, if both static and dynamic libraries exit in the same folder, which library will Visual Studio link?
As an example, for the boost filesystem library, the x64 static library file is libboost_filesystem-vc142-mt-x64-1_77.lib and the x64 dynamic library files are boost_filesystem-vc142-mt-x64-1_77.dll and boost_filesystem-vc142-mt-x64-1_77.lib. All these files are located in the same folder. When linking, how does Visual Studio linker know which one to use? Is it determined by the flag Runtime Library (/MT and /MD)?
CodePudding user response:
TLDR: Yes, in case of boost
choise is based on selected runtime in the project options (/MT or /ST).
Long version: =)
Boost
library has an autolinking feature. This mechanism is defined in the header file config/auto_link.hpp
. There boost is trying to determine full lib name basing on selected build architecture, toolset, threading options and so on. There are defines like BOOST_DYN_LINK
, BOOST_AUTO_LINK_NOMANGLE
which allow you to control this process. Also process could be controlled by library section specific defines for example: BOOST_ASIO_DYN_LINK
for the boost::asio
Relevant section for selecting static/runtime library looks like this:
#if (defined(_DLL) || defined(_RTLDLL)) && defined(BOOST_DYN_LINK)
# define BOOST_LIB_PREFIX
#elif defined(BOOST_DYN_LINK)
# error "Mixing a dll boost library with a static runtime is a really bad idea..."
#else
# define BOOST_LIB_PREFIX "lib"
#endif
Basicaly it depends on _DLL
or _RTLDLL
preprocessor option. According to MSDN
_DLL Defined as 1 when the /MD or /MDd (Multithreaded DLL) compiler option is set. Otherwise, undefined.
For other libraries you must specify exact library name to link against. This is done either in project options window (Linker/Input in case of MSVC), or by using directive #pragma comment(lib libname)
directly in the source code. Failure to do that will lead to linker errors