cython编译错误:函数的多重定义

han*_*ang 4 python compiler-errors cython

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

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

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

import cython
cdef extern void hello_1()
Run Code Online (Sandbox Code Playgroud)

安装文件如下:

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'])
    ])
Run Code Online (Sandbox Code Playgroud)

当我运行安装文件时,它总是报告hello_1并且hello_2有多个定义.谁能告诉我这个问题?

aba*_*ert 7

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

但如果我解决了所有明显的问题,一切都会奏效.那么,让我们来看看所有这些:

setup.py错过了顶部的导入,所以它会NameError立即失败.

接下来,有多个typos- ExtensonExtension,buld_extbuild_ext了,我想多一个,我固定的,但不记得了.

我删除了numpy和openmp的东西,因为它与你的问题无关,而且更容易让它脱离困境.

当您修复所有这些并实际运行设置时,下一个问题立即显而易见:

$ python setup.py build_ext -i
running build_ext
cythoning test.pyx to test.c
Run Code Online (Sandbox Code Playgroud)

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

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

所以:


ctest.c:

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

test.pyx:

import cython
cdef extern void hello_1()
Run Code Online (Sandbox Code Playgroud)

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'])
    ])
Run Code Online (Sandbox Code Playgroud)

运行它:

$ 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
>>>
Run Code Online (Sandbox Code Playgroud)

田田.

  • 多重定义是因为c文件名与将由cython生成的c文件相同.所以解决方案是更改c文件名.非常感谢你. (4认同)