MATLAB: LINK : warning LNK4098: defaultlib ‘MSVCRTD’ conflicts with use of other libs; use /NODEFAULTLIB:library

MATLABmex

I approach building MEX files by the following process:
  • In Visual Studio, I build a static library "code.lib".
  • In Matlab, I build a single .cpp source "matlab_code.cpp" file and link it together statically with code.lib.
For the purposes of debugging, "code.lib" is linked with debug C-runtime (flag /MDd, msvcrtd.lib).
However, mex build step uses release C-runtime (flag /MD, msvcrt.lib).
The result: LINK : warning LNK4098: defaultlib 'MSVCRTD' conflicts with use of other libs; use /NODEFAULTLIB:library.
The diagnosis is clear: we are now mixing two incompatible versions of C runtimes. The solution is also clear: one of them has to be removed so that there is only one version.
I thought this would be solved by adding the -g flag for debugging. However, after adding the -g flag, mex still uses the /MD flag; i.e. the choice of runtime is not affected by the debugging flag.
Am I forced to make my build of code.lib with release C-runtimes instead?
Or is there another way to solve the conflict? Bonus points if I don't have to edit the mexfile, because that complicates the build process.

Best Answer

The solution was to add the flag
-g COMPFLAGS="$COMPFLAGS /MDd"