Cython编译错误:函数重复定义。

5
我创建了一个名为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 生成的文件覆盖。 - abarnert
我之前发布的文件并不完全与我所拥有的相同,而且我也犯了一些错别字。我已经纠正了我的问题。我在这里唯一的问题是因为C文件名与Cython自动生成的C文件名相同。谢谢你的帮助。 - hanqiang
1个回答

9
您发布的文件存在多个问题,我不知道哪一个会导致您的实际代码出现问题 - 特别是因为您展示的代码不可能产生这些错误。但是如果我解决了所有明显的问题,一切都能正常工作。所以,让我们逐一分析它们:您的setup.py缺少顶部的imports,因此将立即失败并出现NameError错误。接下来,有多个拼写错误 - Extenson应为Extension,buld_ext应为build_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
>>>

哒啦。


4
出现多个定义的原因是C文件名与Cython生成的C文件名相同,解决方法是更改C文件名。非常感谢。 - hanqiang

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