在Cython中编译C和C ++源代码

问题描述 投票:1回答:2

我试图在Cython中同时编译C和C ++源代码。这是我当前的设置:

-setup.py

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
import os

language = "c++"
extra_compile_flags = ["-std=c++17"]
os.environ["CC"] = "clang++"

ext_modules = [
    Extension(
        name="Dummy",
        sources=["mydummy.pyx", "source1.cpp","source2.c"],
        language=language,
        extra_compile_args=extra_compile_flags,
   )
]

ext_modules = cythonize(ext_modules)

setup(
    name="myapp",
    ext_modules=ext_modules,
)

-编译命令:

python3 setup.py build_ext --inplace --verbose

在日志中,我收到以下消息:

clang++ -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I. -I/usr/include/python3.6m -I/usr/include/python3.6m -c /path/source2.c -o build/temp.linux-x86_64-3.6/./path/source2.o -std=c++17 -O3
clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is deprecated [-Wdeprecated]

编辑不顺利,但是警告看起来很讨厌。我该如何摆脱呢?天真的解决方案

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

error: invalid argument '-std=c++17' not allowed with 'C'失败

c++ compiler-errors clang cython clang++
2个回答
2
投票

在pyx文件顶部指定语言:

#distutils: language = c++

从setup.py中删除语言参数(将从文件名中推断出来。)>

The documentation says(重点是我的)

语言–要全局启用C ++模式,您可以传递language='c++'。否则,这将基于编译器指令在每个文件级别确定。这仅影响基于文件名找到的模块。传递到cythonize()的扩展实例将不会更改。 建议使用编译器指令# distutils: language = c++,而不要使用此选项。


[这种方法对我来说最有意义:.pyx文件“知道”它是C还是C ++,但不一定表示setup.py应该“知道”或关心它。


我不知道是否存在将不同的编译器标志传递给C和C ++的干净方法(例如-std=c++17)。您可能最好改用os.environ['CXXFLAGS']


0
投票

gcc(或clang)只是一个前端,在给定编译文件的文件扩展名的情况下,它调用适当的编译器(c或c ++编译器)(。c表示应使用c-compiler编译,而.cpp表示它应使用c ++-compiler进行编译),例如,参见类似的SO-issue

© www.soinside.com 2019 - 2024. All rights reserved.