如何确定将为 Python C 扩展调用哪个特定的编译器:GCC 还是 Clang?

18

我有一个Python C++扩展,当在OS X上使用Clang编译时需要以下编译标志:

CPPFLAGS='-std=c++11 -stdlib=libc++ -mmacosx-version-min=10.8'
LDFLAGS='-lc++'

检测我的 setup.py 中的 OS X 相当容易。我可以这样做:

if sys.prefix == 'darwin':
    compile_args.append(['-mmacosx-version-min=10.8', '-stdlib=libc++'])
    link_args.append('-lc++')

(完整上下文请见 这里)

然而,在 GCC 上,这个编译标志是无效的。因此,如果我按照这种方式编写 setup.py,那么当有人试图在 OS X 上使用 GCC 时,编译将会失败。

GCC 和 Clang 支持不同的编译器标志。因此,我需要知道哪个编译器将被调用,以便我可以发送不同的标志。在 setup.py 中检测编译器的正确方法是什么?

编辑1:
请注意,编译错误不会引发任何 Python 异常:

$ python setup.py build_ext --inplace
running build_ext
building 'spacy.strings' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -c spacy/strings.cpp -o build/temp.linux-x86_64-2.7/spacy/strings.o -O3 -mmacosx-version-min=10.8 -stdlib=libc++
gcc: error: unrecognized command line option ‘-mmacosx-version-min=10.8’
gcc: error: unrecognized command line option ‘-stdlib=libc++’
error: command 'gcc' failed with exit status 1
$

当您向GCC传递错误的标志时(在Python脚本中),会发生什么异常?正确的方法是 try: send_flags_for_clang() except ThatException: send_flags_for_gcc() - Two-Bit Alchemist
没有引发任何异常。 - syllogism_
3个回答

4

我因需要同样类型的开关而遇到了你的问题。此外,在我的情况下,sys.prefix并不理想,因为无论平台如何,标志都是面向clang的。

我不确定它是否完美,但这是对我最有效的解决方案。所以,我检查是否设置了CC变量;如果没有,我会检查我猜测的distutils位置。

欢迎任何更好的解决方案!

import os
import distutils

try:
    if os.environ['CC'] == "clang":
        clang = True
except KeyError:
    clang = False

if clang or distutils.sysconfig_get_config_vars()['CC'] == 'clang':
    try:
        _ = os.environ['CFLAGS']
    except KeyError:
        os.environ['CFLAGS'] = ""
    os.environ['CFLAGS'] += " -Wno-unused-function"
    os.environ['CFLAGS'] += " -Wno-int-conversion"
    os.environ['CFLAGS'] += " -Wno-incompatible-pointer-types

对于不太开心的人:我本来想使用extra_compile_args选项,但它会将标志放在clang编译命令的错误位置。


1
这里不需要try语句,因为get()key in d已经可以胜任。 - EvgenKo423

4
将以下代码添加到您的setup.py文件中。它会明确检测编译器接受哪些标志,然后只添加这些标志。
# check whether compiler supports a flag
def has_flag(compiler, flagname):
    import tempfile
    from distutils.errors import CompileError
    with tempfile.NamedTemporaryFile('w', suffix='.cpp') as f:
        f.write('int main (int argc, char **argv) { return 0; }')
        try:
            compiler.compile([f.name], extra_postargs=[flagname])
        except CompileError:
            return False
    return True


# filter flags, returns list of accepted flags
def flag_filter(compiler, *flags):
    result = []
    for flag in flags:
        if has_flag(compiler, flag):
            result.append(flag)
    return result


class BuildExt(build_ext):
    # these flags are not checked and always added
    compile_flags = {"msvc": ['/EHsc'], "unix": ["-std=c++11"]}

    def build_extensions(self):
        ct = self.compiler.compiler_type
        opts = self.compile_flags.get(ct, [])
        if ct == 'unix':
            # only add flags which pass the flag_filter
            opts += flag_filter(self.compiler,
                                '-fvisibility=hidden', '-stdlib=libc++', '-std=c++14')
        for ext in self.extensions:
            ext.extra_compile_args = opts
        build_ext.build_extensions(self)

setup(
   cmdclass=dict(build_ext=BuildExt),
   # other options...
)
< p >这个has_flag方法是从pybind11的这个例子中获取的。 https://github.com/pybind/python_example


1

这里有一个跨编译器和跨平台的解决方案:

from setuptools import setup
from setuptools.command.build_ext import build_ext


class build_ext_ex(build_ext):

    extra_args = {
        'extension_name': {
            'clang': (
                ['-std=c++11', '-stdlib=libc++', '-mmacosx-version-min=10.8'],
                ['-lc++']
            )
        }
    }

    def build_extensions(self):
        # only Unix compilers and their ports have `compiler_so`
        compiler_cmd = getattr(self.compiler, 'compiler_so', None)
        # account for absolute path and Windows version
        if compiler_cmd is not None and 'clang' in compiler_cmd[0]:
            self.cname = 'clang'
        else:
            self.cname = self.compiler.compiler_type

        build_ext.build_extensions(self)

    def build_extension(self, ext):
        extra_args = self.extra_args.get(ext.name)
        if extra_args is not None:
            extra_args = extra_args.get(self.cname)
            if extra_args is not None:
                ext.extra_compile_args = extra_args[0]
                ext.extra_link_args    = extra_args[1]

        build_ext.build_extension(self, ext)


setup(
    ...
    cmdclass = {'build_ext': build_ext_ex},
    ...
)

...以及支持的编译器类型列表(由setup.py build_ext --help-compiler返回):

--compiler=bcpp     Borland C++ Compiler
--compiler=cygwin   Cygwin port of GNU C Compiler for Win32
--compiler=mingw32  Mingw32 port of GNU C Compiler for Win32
--compiler=msvc     Microsoft Visual C++
--compiler=unix     standard UNIX-style compiler

如果你面临与 @xoolive 相同的问题,只需重写 build_extensions(self) 并将选项附加到 self.compiler.compiler_soself.compiler.linker_so 的末尾即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接