Tell setuptools what compiler to use

Hi folks.
I have looked at the setuptools documentation but I’m still confused about this.
I have a C program that I compile to a Python module, which uses gcc specific settings in the code. Therefore, if I want to compile the code on Windows, I need to use MinGW or something similar.

My current setup has a pyproject.toml file that specifies almost everything, and a setup.py script that compiles the C code using the cffi package. As far as I can tell, cffi defers to setuptools to actually compile the C code, so it’s setuptools that I need to tell to use MinGW on windows.

I have tried a number of different solutions so far. The only thing that has worked is creating a setup.cfg file and adding

[build_ext]
compiler=mingw32

But this would only work on Windows, and I want the program to be installable on Linux and MacOS as well.

I also tried this:
https://setuptools.pypa.io/en/latest/userguide/ext_modules.html
which says:

The command build_ext builds C/C++ extension modules. It creates a command line for
running the compiler and linker by combining compiler and linker options from various sources:

  • the sysconfig variables CC, CXX, CCSHARED, LDSHARED, and CFLAGS,
  • the environment variables CC, CPP, CXX, LDSHARED and CFLAGS, CPPFLAGS, LDFLAGS,

I tried setting CC=gcc but this didn’t seem to have any effect, setuptools seems to have ignored the flag and used Visual Studio C++, which is not what I want. I am also confused as to why the compiler field in build_ext accepts mingw32, should I be using CC=mingw32 ?

This blog post seems relevant but creating a custom extension class seems overkill, I was wondering if there’s a simpler way to solve this problem, using a flag that can be dynamically passed to the compiler. As I said, I tried setting the environment variables but nothing happened.

This was the way that I used as well. I made a script to generate a setup.cfg with these contents when building wheels in CI:

The proper fix in the end was migrating from setuptools to meson-python. With meson-python the build detects mingw automatically if you build in an msys shell. It is also much easier to configure all of your other build settings and compiler options with meson than with setuptools.