如何编译cython代码

时间:2016-09-23 17:02:37

标签: python cython

我想编译我的代码。我想编写自己的cpp文件来调用其他库中的函数。

我的cpp代码

//my_vl.h
int my_vl_k(int normalized_feat_set, int k){}

我的pxd文件

#my_vl.pxd
import libc.stdlib

cdef extern from "my_vl.h":
    int my_vl_k(int normalized_feat_set, int k)

我知道我现在不需要.h文件和.pxd文件,但这是一个很好的做法,如果你可以帮助我如何包含它也会有所帮助。

我的cpp文件:

//my_vl.cpp    
extern "C" {
  #include <vl/random.h>
  #include <vl/generic.h>
  #include <vl/kmeans.h>
  #include <vl/mathop.h>
}

#include <cstdlib>
#include <stdio.h>


int my_vl_k(int normalized_feat_set, int K){
  int r = 5;
return r;
}

我的pyx文件:

#my_vl.pyx
cimport my_vl


cdef extern from "my_vl.cpp":
    int my_vl_k(int, int)

我的设置文件:

#setup.my_val.py
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext


sourcefiles = ['my_vl.pyx', 'my_vl.cpp']
ext_modules = [Extension("my_vl", 
                          sourcefiles,
                          include_dirs = ['/path/to/vlfeat-0.9.20'],
                           libraries = ['vl'],
                          library_dirs = ['/path/to/vlfeat-0.9.20/bin/glnxa64/']
                          )]

setup(
  name = 'my_val app',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules
)
我得到的错误是:

python setup.my_val.py build_ext --inplace
running build_ext
skipping 'my_vl.c' Cython extension (up-to-date)
building 'my_vl' extension
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/path/to/vlfeat-0.9.20 -I/usr/include/python2.7 -c my_vl.cpp -o build/temp.linux-x86_64-2.7/my_vl.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/path/to/vlfeat-0.9.20 -I/usr/include/python2.7 -c my_vl.cpp -o build/temp.linux-x86_64-2.7/my_vl.o
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
c++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/my_vl.o build/temp.linux-x86_64-2.7/my_vl.o -L/path/to/vlfeat-0.9.20/bin/glnxa64/ -lvl -o /mnt/disk2/work/visual_clusters/my_vl.so
build/temp.linux-x86_64-2.7/my_vl.o: In function `my_vl_k(int, int)':
/path/to/my_vl.cpp:45: multiple definition of `my_vl_k(int, int)'
build/temp.linux-x86_64-2.7/my_vl.o:/path/to/my_vl.cpp:45: first defined here
collect2: error: ld returned 1 exit status
error: command 'c++' failed with exit status 1

不确定我要做什么

2 个答案:

答案 0 :(得分:0)

在my_v1.h中你应该使用标题保护:

my_v1.h:

#ifndef MY_V1_H
#define MY_V1_H

// your function decl.

#endif

答案 1 :(得分:0)

您在头文件(Ctrl)中提供了my_vl_k的定义。而是写

{}

(用一个分号替换提供无用空定义的大括号,只是说该函数存在)。