Cython:为什么"重复符号"?

时间:2017-02-15 21:41:05

标签: c++ cython

我是Cython的新手,所以如果这是一个菜鸟问题,请原谅我。我试图将primes example修改为纯c ++(。h / .cpp)实现,然后由.pyx文件包装。

primes.h:

#include <list>

std::list<int> primes2_c(int maxn);

primes.cpp

#include "primes.h"

#include <list>

std::list<int> primes2_c(int maxn) {
    int n;
    std::list<int> ret;
    n = 2;
    while (n < maxn) {
        auto it = ret.begin();
        for (; it != ret.end() && n % *it != 0; it++);
        if (it == ret.end()) {
            ret.push_back(n);
        }
        n++;
    }

    return ret;
}

primes.pyx

cdef extern from "primes.h":
    list[int] primes2_c(int)

def primes2(kmax):
    ret = primes2_c(kmax)
    return ret

primes.setup

from distutils.core import setup, Extension
from Cython.Build import cythonize

setup(
    name='primes',
    ext_modules=cythonize(Extension(
        'primes',
        ['primes.pyx', 'primes.cpp'],
        language='c++',
        extra_compile_args=["-std=c++11"],
        extra_link_args=["-std=c++11"],
    ))
)

然后我运行编译并看到这个错误:

[cython (master)]$ python primes.setup build_ext --inplace
running build_ext
building 'primes' extension
/usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I/Users/.../venv/cython/include -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c primes.cpp -o build/temp.macosx-10.6-intel-3.5/primes.o -std=c++11
/usr/bin/clang -fno-strict-aliasing -Wsign-compare -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -arch i386 -arch x86_64 -g -I/Users/.../venv/cython/include -I/Library/Frameworks/Python.framework/Versions/3.5/include/python3.5m -c primes.cpp -o build/temp.macosx-10.6-intel-3.5/primes.o -std=c++11
/usr/bin/clang++ -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/temp.macosx-10.6-intel-3.5/primes.o build/temp.macosx-10.6-intel-3.5/primes.o -o /Users/.../cython/primes.cpython-35m-darwin.so -std=c++11
clang: warning: libstdc++ is deprecated; move to libc++ with a minimum deployment target of OS X 10.9
clang: warning: libstdc++ is deprecated; move to libc++ with a minimum deployment target of OS X 10.9
duplicate symbol __Z9primes2_ci in:
    build/temp.macosx-10.6-intel-3.5/primes.o
ld: 1 duplicate symbol for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command '/usr/bin/clang++' failed with exit status 1
[cython (master)]$

我的理解是 primes.pyx 只读取primes2_c()的API而不是实现。因此,为同一函数提供的唯一实现应该来自 primes.setup 中对 primes.cpp 的引用。

1 个答案:

答案 0 :(得分:2)

您可以将primes.cpp重命名为例如primesc.cpp?我认为primes.pyx由Cython编译为primes.cpp作为构建的一部分,因此存在文件名冲突。