Using mingw-w64 with Custom CRT
This article is based on mingw-w64 version 10, which is included with Debian Bookworm. It should be pretty straightforward to do the same thing with other mingw-w64 versions.
Why would you need this?
Compiling standard library for a different CPU may yield more compatibility.
In my case, I would like to support CPUs starting from i486, while Debian-provided crt is built with i686 instructions.
In this situation you do not need to rebuild the whole compiler, only crt (standard library).
Compiling CRT
Download the sources for your version of mingw-w64 and unpack them to a directory.
Before calling the configure script you need to set CFLAGS and CXXFLAGS to the cpu you need.
export CFLAGS="-march=i486 -O2"
export CXXFLAGS="-march=i486 -O2"
export CPPFLAGS="-march=i486 -O2"
Important note is that if you omit -O2 here, you're not getting optimised code.
Then you need to specify proper msvcrt, in my case -- msvcrt-os which corresponds to msvcrt.dll, available in Visual C Redistributable 4.0 - 6.0.
Mingw-w64 recommends using a separate folder for building, so I suggest doing the same -- just run configure from the build directory.
path-to-mingw-w64/mingw-w64-crt/configure\
--host=i686-w64-mingw32\
--target=i486-w64-mingw32\
--with-default-msvcrt=msvcrt-os\
--prefix=crt_prefix
make
make install
Take note that make install will copy your new crt into the prefix path you specify, so unless you want to mess up your OS you should specify a custom path.
Using the compiled CRT
To build something with your new crt instead of the system one you can pass it with a -B parameter in CFLAGS
export CFLAGS="-Bcrt_prefix/lib"
Take note that you need the actual directory with .a/.o files for the compiler to find them. Also note that if you specify incorrect path, the compiler will use the built-in CRT, without raising any error.