Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a different C++ compiler in Cython?

I'm working on a project to call C++ from Python. We use Cython for this purpose. When compile by using the command "python3.6 setup.py build_ext --inplace", the compiler "x86_64-linux-gnu-gcc" is used. Is there a way to use a different compiler like "arm-linux-gnueabihf-g++"?

Also, is there a way to add a compilation option such as "-DPLATFORM=linux"?

Here's the setup.py:

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules = cythonize(Extension(
    "app",
    sources=["app.pyx", "myapp.cpp"],
    language="c++",
    include_dirs=["../base"]
)))
like image 762
user1556331 Avatar asked Jul 23 '19 22:07

user1556331


3 Answers

Distutils by default uses the CC system environment variable to decide what compiler to use. You can run the python script such that the CC variable is set to whatever you want at the beginning of the script before setup() is called.

As for passing flags to the compiler, add a extra_compile_args named argument to your Extension() module. It may look like this for example:

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(ext_modules = cythonize(Extension(
    "app",
    sources=["app.pyx", "myapp.cpp"],
    language="c++",
    include_dirs=["../base"],
    extra_compile_args=["-DPLATFORM=linux"]
)))
like image 162
JSON Brody Avatar answered Oct 06 '22 15:10

JSON Brody


You can fix the value of the CC environment variable in setup.py. For instance:

os.environ["CC"] = "g++"

or

os.environ["CC"] = "clang++"
like image 38
Rexcirus Avatar answered Oct 06 '22 14:10

Rexcirus


In order to specify a C++ compiler for Cython, you need to set a proper CXX environment variable prior calling setup.py.

This could be done:

  • Using a command-line option:
export CXX=clang++-10
  • In the setup.py:
os.environ["CXX"] = "clang++-10"

Note: clang++-10 is used as an example of the alternative C++ compiler.

Note: CC environment variable specifies C compiler, not C++. You may consider specifying also e.g. export CC=clang-10.

like image 1
Ales Teska Avatar answered Oct 06 '22 16:10

Ales Teska