I am trying to expose some c++ code to Python with pybind11. I specifically would like to enforce a certain c++ standard (say c++11), as the same .cpp file would need to be compiled on different systems. Following the official example to compile with setuptools in this repository, I modified part of the code as follows:
ext_modules = [
Pybind11Extension(
modulename,
sources=[filename],
language='c++',
cxx_std=11
),
]
I ran python setup.py install
on my windows machine and a Linux machine (it's actually Google Colab, which uses Linux backend). I checked the standard used by adding py::print(__cplusplus);
in code. On the Linux machine, the standard changed from c++14 to c++ 11 after adding cxx_std=11
. However, on my own windows machine, the standard remained as c++98. In both cases, the exposed code can be sucefully imported as a module (a .pyd file on windows and a .so file on linux) and works as intended. This is very strange because:
(1) According to the documentation for Pybind11Extension
, it "Build a C++11+ Extension module with pybind11.". It does not make sence for my code to be compiled with c++98 successfully when the minimum requirement is c++11.
(2) I have gcc version 8.1.0 (by checking g++ -v
), which should support the latest standard of c++. Additionally, if I use g++ command to compile a normal cpp file, it says c++14, which means c++14 is the default.
This difference of standard is causing a lot of trouble because sometimes code works on my windows machine but fails when compiled on Linux.
Now, I am relatively new to stuff about c++ compilers, so I might be missing something obvious. Any idea how to solve this?
Update: After some discussion it seems that setup.py
uses MSVC on windows. This question then becomes a duplicate of this, which remains unsolved (the setup.cfg
method mentioned does not work. I could specify --compiler msvc
but if I write --compiler mingw32
it raise several errors: gcc: error: /EHsc: No such file or directory
, gcc: error: /bigobj: No such file or directory
, gcc: error: /std:c++14: No such file or directory
).
Update 2: With the method by spectras it is confirmed that setup.py
uses MSVC, which also has c++14 as earlist possible standard. However, I still want to enforce GCC so I could have the same compiler on windows and linux. To enforce GCC, I tried the following command (env_csmar is an anaconda virtual environment under my disk F):
D:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\gcc.exe -static -shared -std=c++11 -DMS_WIN64 -fPIC "-IF:\...\env_csmar\lib\site-packages\pybind11\include" "-IF:\...\env_csmar\include" "-L F:\...\env_csmar\libs" -c example_cpp.cpp -o example_cpp.o
This works, and the .o file can be imported as a module on my windows. However, it still says it is compiled with MSVC and under c++14 (from #ifdef _MSVC_LANG
). Why is this?