SWIG Python undefined symbol error

帅比萌擦擦* 提交于 2019-12-05 15:05:49
Oliver

You must link the library that defines your C++ functions that you have declared like checkStop etc. You would add -L<path to your C++ DLL> -l<name of your C++ DLL> on 3rd line of your example's compile steps.

Like this:

c++ -L<path to DLL> -l<name of your dll> -shared spiController_wrap.o -o _spiController.so

I just got the same error and finally figured out why. As above people said, when it says unfound symbol like yours and gives the undefined function name '_Z9checkStopv', always check for the implementation of this function in .cpp file as well as any function declaration of the same name!!

For my case, my cpp does define my 'unfound symbol' constructor function, but in my .h file, i have an overloaded operator= (for the constructor) which is undefined in .cpp file. So swig wraps both default constructor(implemented in .cpp) and operator= (not implemented). Therefore when import, this unimplemented operator= produces the error. Hope this helps!

Just as Adam's comment and my experience, you should first compile your XXX.cpp file into XXX.o, the whole command lines maybe like following:

1. swig -python -c++ XXX.i

2. c++ -c -fpic XXX.cpp (this command will generate XXX.o file)

3. c++ -c -fpic XXX_wrap.cxx -I/usr/include/python2.7 (this command will generate XXX_wrap.o file)

4. c++ -shared XXX.o XXX_wrap.o -o XXX.so

Although there may be many causes for this problem, I got the exact same error when I compiled the shared library with the python v3.5 headers, e.g.

swig -python example.i
gcc -fPIC -c example.c example_wrap.c -I/usr/include/python3.5 # <-- ISSUE HERE
gcc -shared example.o example_wrap.o -o _example.so

But then later tried to use the example library using python test.py, which ran python v2.7 on system (so it was a python version mismatch issue).

In my case I was also getting that error, and spent some time trying out stuff without success. My problem was that although my source file was plain C I had it named with the .cpp extension, assuming it wouldn't matter. Changing the extension to .c solved automatically the issue.

Another way of solving it was to add the line #include "example.cpp" to the header section of SWIG's .i file.

So, summarizing:

example.c

int fact(int n) {
  if (n <= 1) return 1;
  else return n*fact(n-1);
}

example.i

%module example
%{
  extern int fact(int n);
%}
extern int fact(int n);

Then the following worked for me (in Ubuntu 17.10):

swig -c++ -python example.i
gcc -fPIC -c example.c example_wrap.c -I /usr/include/python2.7
gcc -shared example.o example_wrap.o -o _example.so
python -c "import example; print example.fact(5)"

Hope this helps someone!
Cheers

I know the solution At the end of make up the share,you should usr g++ -shared -fpic *.o *.o -o _***.so

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!