Should I link to the Visual Studio C runtime statically or dynamically

crtmsvcrt

I have read arguments on both sides about whether one should link to the C runtime library statically or dynamically in Visual Studio projects, and I'm still not entirely sure what to think.

My project pulls in some third-party libraries (Python, HDF5, Trilinos, and Microsoft MPI), each of which has to be built with the same runtime library as my final executable (otherwise they cannot be linked together). When linking statically, each of these libraries will contain a copy of the C runtime. I read that this is liable to cause issues because the final executable will contain multiple copies of the runtime, none of which can interact with each other. But wouldn't the linker complain if the same symbols were multiply defined?

I would like to avoid "DLL Hell" but am worried about insidious errors that could arise from statically linking in multiple copies of the runtime. Am I reading things wrong?

Also, I'm using Visual Studio 2005 and I read that the Service Pack 1 runtime is not backwards-compatible. Does this mean that an app built without SP1 will not run on a machine that has the SP1 dlls, even if they have the same name (e.g. msvcr80.dll)?

Best Answer

Linking statically will bloat all your EXEs and DLLs, and can cause crashes (eg. if code in one DLL calls free() with a pointer allocated by malloc() in a different DLL).

You can get the best of both worlds by linking dynamically and deploying the runtime DLLs as private assemblies. This simply means putting a copy of a specially-named directory containing the runtime DLLs and their manifests next to your executable.

See the section "Deploying Visual C++ library DLLs as private assemblies" at http://msdn.microsoft.com/en-us/library/ms235291(VS.80).aspx for details, but basically your application looks like this:

c:\Program Files\My App\MyApp.exe
c:\Program Files\My App\MyLibrary.dll
c:\Program Files\My App\Microsoft.VC80.CRT\Microsoft.VC80.CRT.manifest
c:\Program Files\My App\Microsoft.VC80.CRT\msvcr80.dll

As to your last question, yes, the target machine needs the correct versions of the runtime DLLs to work, but by deploying them as private assemblies, you guarantee that.

Another benefit is that non-admin users can install your app (not into Program Files, but elsewhere) - they don't need permission to write files into the WinSxS area.

Related Topic