When building a DLL; what type of CRT should I lin

2019-05-06 19:19发布

问题:

In windows; there are 2 options to link to a CRT:

  1. Multithreaded, static link
  2. Multithreaded, dynamic link

Can someone shed some light on what is the best practice here? Should I link 'statically' to the CRT or do a dynamic link?

If i do a dynamic link, and I write a program that uses my DLL + another 3rd party DLL (which is doing a static link to CRT), is that an issue?

回答1:

This is a Big Deal when you use DLLs in your application. It is very important that the EXE and the DLLs use the same memory allocator. In case you return pointers or C++ objects (like std::string) from a DLL function that needs to be released by the caller. To get the same allocator, all modules must use the same instance of the CRT. You only get that if you compile with /MD to select the DLL version of the CRT. And they must all use the same version of the CRT. Using /MT anyway causes very hard to diagnose memory leaks, an access violation if you're lucky.

Using /MT makes it easier to deploy your app since you don't have to install the runtime DLLs. As implied, this is only safe to do if you only have to deploy an EXE. Or when you very carefully control the public interface of your DLLs. An automation compatible COM server for example can link to the static version of the CRT. Automation has strict rules about exchanging pointers and managing memory.