5

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?

xav
  • 5,452
  • 7
  • 48
  • 57
shergill
  • 3,738
  • 10
  • 41
  • 50

1 Answers1

5

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • @Hans Surely all sane development involves allocating and deallocating in the same library (where by library I am allowing for possibly multiple DLLs, or an EXE and some DLLs). In which case surely you can link either static or dynamic CRT and the choice comes down to preference and hygiene factors. – David Heffernan Mar 10 '11 at 19:16
  • @David : do you think it is sane to return an std::string from a function? The DLL allocates it, the EXE releases it. Dynamic CRT required. – Hans Passant Mar 10 '11 at 19:26
  • @David: no it doesn't. The mistake can be as subtle as mixing the debug version of one library with the release version of another - even when dynamically linking. For anything beyond that there is `IMalloc`. – 0xC0000022L Mar 10 '11 at 19:29
  • @Hans I always avoid having memory ownership cross module boundaries. – David Heffernan Mar 10 '11 at 19:29
  • 1
    is there a link that explores this topic in more detail? – shergill Mar 10 '11 at 22:34
  • 1
    The MSDN library article for /MD has a reference to a KB article and links: http://msdn.microsoft.com/en-us/library/2kzt1wy3%28v=VS.100%29.aspx – Hans Passant Mar 10 '11 at 23:02