【问题标题】:Python C extension with openmp for OS X用于 OS X 的带有 openmp 的 Python C 扩展
【发布时间】:2016-10-25 08:17:47
【问题描述】:

我为 C 程序创建了一个 python 扩展。在linux中,使用gcc,一切正常,可以安装扩展输入:

sudo python setup.py install

但是当我尝试在 OS X 中使用它时:

GCC 4.7:

我已经使用 macports 安装了 gcc 4.9,并在我的 setup.py 文件中添加了这一行

import os
os.environ["CC"]="gcc-mp-4.9"

当我输入sudo python setup.py install

我收到此错误:

unrecognized command line option '-Wshorten-64-to-32'

我一直在寻找解决方案,每个人都说“使用 clang 而不是 gcc”来解决这个问题。

Clang 3.8:

我还安装了clang 3.8(os X中安装了3.5但没有openmp)并且我修改了setup.py文件:

import os
os.environ["CC"]="clang-mp-3.8"

我得到这个错误:

unknown argument: '-mno-fused-madd'

在一些论坛中,我找到了解决此问题的可能解决方案,为 CFLAGS 设置一个空值:

sudo CFLAGS="" python setup.py install

但是我得到一个新的错误:

library not found for -lgomp

我使用 -fopenmp 但我不知道为什么调用 -fgomp。在一些论坛上,人们说我必须使用gcc而不是clang,所以我又回到了起点。

我想找到一个解决方案来轻松地在 OS X 中安装这个扩展,因为我想创建一个任何人都可以轻松安装的扩展。

【问题讨论】:

    标签: python c gcc clang


    【解决方案1】:

    我遇到了类似的问题。 Python 使用 clang 构建并使用特定于 clang 的 CFLAGS:

    >>> import sysconfig
    >>> sysconfig.get_config_var("CFLAGS")
    '-fno-strict-aliasing -fno-common -dynamic -arch x86_64
    -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing
    -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall
    -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g
    -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE'
    

    Distutils 将此信息复制到“UnixCCCompiler”实例,用于制作扩展。但是,正如您所发现的,-Wshorten-64-to-32 是特定于 clang 的。

    我的解决方案是修改 distutils 构建扩展的方式。下面从命令行参数列表中删除该选项以在调用真正的编译代码之前传递给编译器。 (你的代码可能不需要那么复杂。我支持几种编译器和配置。)

    def _is_gcc(compiler):
        return "gcc" in compiler or "g++" in compiler
    
    class build_ext_subclass( build_ext ):
        def build_extensions(self):
            c = self.compiler.compiler_type
            if c == "unix":
                compiler_args = self.compiler.compiler
                c = compiler_args[0]  # get the compiler name (argv0)
                if _is_gcc(c):
                    names = [c, "gcc"]
                    # Fix up a problem on older Mac machines where Python
                    # was compiled with clang-specific options:
                    #  error: unrecognized command line option '-Wshorten-64-to-32'
                    compiler_so_args = self.compiler.compiler_so
                    for args in (compiler_args, compiler_so_args):
                        if "-Wshorten-64-to-32" in args:
                            del args[args.index("-Wshorten-64-to-32")]
    
            build_ext.build_extensions(self)
    

    然后告诉 setup() 使用这个新的子类来构建扩展:

    setup(name = ...
          cmdclass = {"build_ext": build_ext_subclass},
         )
    

    【讨论】:

      猜你喜欢
      • 2017-03-12
      • 2013-02-15
      • 2011-04-04
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多