62

我知道使用与构建 Pythonsetup.py相同的方法。CFLAGS我有一个单独的 C 扩展,它是段错误的。我需要在没有 -O2的情况下构建它,因为-O2正在优化一些值和代码,因此核心文件不足以确定问题。

我只需要修改setup.py以便-O2不使用。

我已经阅读distutils了文档,特别是distutils.ccompilerdistutils.unixccompiler查看了如何添加标志和库以及包含,但没有阅读如何修改默认的 GCC 标志。

具体来说,这是针对 Python 2.5.1 上的遗留产品,带有一堆反向端口(Fedora 8,是的,我知道......)。不,我无法更改操作系统或 Python 版本,也无法重新编译 Python。我只需要为一个环境是唯一一个段错误的客户构建一个 C 扩展。

4

3 回答 3

79
  • 在运行CFLAGS="-O0"之前添加setup.py

    % CFLAGS="-O0" python ./setup.py
    

    将在编译时-O0附加CFLAGS,因此将覆盖先前的-O2设置。

  • 另一种方法是添加-O0到:extra_compile_argssetup.py

    moduleA = Extension('moduleA', .....,
            include_dirs = ['/usr/include', '/usr/local/include'], 
            extra_compile_args = ["-O0"], 
            )
    
  • 如果要删除所有默认标志,请使用:

    % OPT="" python ./setup.py
    
于 2012-06-03T00:40:30.500 回答
4

当我需要完全删除一个标志(-pipe)以便在低内存系统上编译 SciPy 时,我遇到了这个问题。我发现,作为 hack,我可以通过编辑 /usr/lib/pythonN.N/_sysconfigdata.py 来删除不需要的标志,以删除该标志的每个实例,其中 NN 是您的 Python 版本。有很多重复,我不确定 setup.py 实际使用了哪些。

于 2020-03-20T00:10:35.800 回答
2

distutils/​<code>setuptools 允许在脚本extra_compile_args中定义 Python 扩展时使用 /​<code>extra_link_args 参数指定任何编译器/链接器标志。setup.py这些额外的标志将在默认标志之后添加,并将覆盖之前存在的任何互斥标志。

但是,对于常规使用,这并没有多大用处,因为您通过 PyPI 分发的包可以由具有不兼容选项的不同编译器构建。
以下代码允许您以特定于扩展和编译器的方式指定这些选项:

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


class build_ext_ex(build_ext):

    extra_compile_args = {
        'extension_name': {
            'unix': ['-O0'],
            'msvc': ['/Od']
        }
    }

    def build_extension(self, ext):
        extra_args = self.extra_compile_args.get(ext.name)
        if extra_args is not None:
            ctype = self.compiler.compiler_type
            ext.extra_compile_args = extra_args.get(ctype, [])

        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
于 2021-07-12T14:46:18.973 回答