Specity C++ compiler in setup.py for Pybind11

Viewed 47

This is a simple question but has been bothering me for 3 months now. When I use the setuptools/setup.py method to compile C++ code into a Python package on my windows os, it always defaults to MSVC, but part of the code uses stdlibc++ which is only accessible with GNU. Is there some way to specify it to MinGW, or somehow change the default behavior? I have looked into other methods, cppimport does not support windows, and the cmake method seems very complex to me.

For reference, a simple test to check whether the compiler is MSVC:

check_compiler.cpp

#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
namespace py = pybind11;


void test(){
    #ifdef _MSVC_LANG
    py::print("Compiled with MSVC. ");
    #else
    py::print("Not compiled with MSVC. ");
    #endif
}


PYBIND11_MODULE(check_compiler, m) {
    m.def("test", &test);
}

setup.py

"""
python setup.py install
"""

from pybind11.setup_helpers import Pybind11Extension
from setuptools import setup
import os
import shutil


ext_modules = [
    Pybind11Extension(
        'check_compiler',
        sources=['check_compiler.cpp'],
        language='c++',
        cxx_std=11
    ),
]

setup(
    name='check_compiler',
    author='XXX',
    ext_modules=ext_modules
)

# copy the package
for filename in os.listdir("dist"):
    if filename.endswith(".egg"):
        shutil.copy(os.path.join("dist", filename), ".")

Then run python setup.py install, an .egg file will be copied from subfolder to the current directory. Finally, run the following:

main.py

import check_compiler

check_compiler.test()

Similar question, but no accepted answer: How can I build a setup.py to compile C++ extension using Python, pybind11 and Mingw-w64?

Update: I was able to specify MinGW with cmake by adding -G "MinGW Makefiles" in the camke command. Still woudl welcome an answer of how to do this with setuptools, as it is the most convenient method.

0 Answers
Related