user1556331
user1556331

Reputation: 395

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"]
)))

Upvotes: 7

Views: 4460

Answers (3)

Ales Teska
Ales Teska

Reputation: 1288

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.

Upvotes: 1

Rexcirus
Rexcirus

Reputation: 2897

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

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

or

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

Upvotes: 3

JSON Brody
JSON Brody

Reputation: 828

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"]
)))

Upvotes: 2

Related Questions