【问题标题】:cython compiling error: multiple definition of functionscython编译错误:函数的多个定义
【发布时间】:2013-10-08 23:20:26
【问题描述】:

我创建了一个名为 test.c 的 c 文件,其中两个函数定义如下:

#include<stdio.h>
void hello_1(void){
    printf("hello 1\n");
}
void hello_2(void){
    printf("hello 2\n");
}

之后,我创建 test.pyx 如下:

import cython
cdef extern void hello_1()

安装文件如下:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(cmdclass={'buld_ext':build_ext}, 
      ext_modules=[Extension("test",["test.pyx", "test.c"], 
                   include_dirs=[np.get_include()],
                   extra_compile_args=['-g', '-fopenmp'],
                   extra_link_args=['-g', '-fopenmp', '-pthread'])
    ])

当我运行安装文件时,它总是报告 hello_1 和 hello_2 有多个定义。谁能告诉我问题所在?

【问题讨论】:

  • 如果这是你的实际代码,至少有两个问题:(1) 你拼错了Extensionbuild_ext,可能还有其他的东西,(2) 你我有一个名为test.c 的文件,它将被test.pyx 生成的文件覆盖。
  • 我之前发的文件和我的不完全一样,还打了一些错别字。我已经纠正了我的问题。我这里唯一的问题是因为c文件名与cython自动生成的c文件相同。感谢您的帮助。

标签: python compiler-errors cython


【解决方案1】:

您发布的文件有很多问题,我不知道是哪一个导致您的实际代码出现问题 - 特别是因为您向我们展示的代码不会也不可能生成那些错误。

但是,如果我解决了所有明显的问题,那么一切正常。所以,让我们来看看所有这些:

您的setup.py 缺少顶部的导入,因此它会立即以NameError 失败。

接下来,有多个拼写错误——ExtensionExtensonbuild_extbuld_ext,我想还有一个我修正了但不记得了。

我去掉了 numpy 和 openmp 的东西,因为它与您的问题无关,而且更容易解决它。

当您修复所有这些并实际运行设置时,下一个问题会立即变得明显:

$ python setup.py build_ext -i
running build_ext
cythoning test.pyx to test.c

您要么用从test.pyx 构建的文件覆盖您的test.c 文件,或者,如果幸运的话,忽略生成的test.c 文件并使用现有的test.c,就好像它是test.pyx 的 cython 编译输出。无论哪种方式,您都在编译同一个文件两次并尝试将结果链接在一起,因此您有多个定义。

您可以将 Cython 配置为对该文件使用非默认名称,或者更简单地说,遵循通常的命名约定,并且首先不要尝试使用 test.ctest.pyx

所以:


ctest.c:

#include <stdio.h>
void hello_1(void){
    printf("hello 1\n");
}
void hello_2(void){
    printf("hello 2\n");
}

test.pyx:

import cython
cdef extern void hello_1()

setup.py:

from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(cmdclass={'build_ext':build_ext}, 
      ext_modules=[Extension("test",["test.pyx", "ctest.c"], 
                   extra_compile_args=['-g'],
                   extra_link_args=['-g', '-pthread'])
    ])

并运行它:

$ python setup.py build_ext -i
running build_ext
cythoning test.pyx to test.c
# ...
clang: warning: argument unused during compilation: '-pthread'
$ python
>>> import test
>>>

多田。

【讨论】:

  • 多重定义是因为c文件名与cython生成的c文件名相同。所以解决办法就是改c文件名。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多