I tried to link pybind11 with a static library. The building process was successful, but I got the runtime error "ImportError: undefined symbol". Directly linking with .o
file worked fine though.
I have no luck with shared libraries either, with the same error. For shared libraries, I moved libadd.so
to /usr/lib
.
An example with a static library is as follows:
/* my_add.cpp */
#include <pybind11/pybind11.h>
#include "add.hpp"
namespace py = pybind11;
PYBIND11_MODULE(my_add, m) {
m.def("add", &add);
}
/* add.hpp */
int add(int x, int y);
/* add.cpp */
#include "add.hpp"
int add(int x, int y) {
return x + y;
}
First, I complied add.cpp
into a static library.
g++ -c add.cpp -o add.o
ar rcs libadd.a add.o
Then, I complied my_add.cpp
and linked it against libadd.a
.
g++ -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) libadd.a my_add.cpp -o my_add$(python3-config --extension-suffix)
In the same directory:
$ python3
Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import my_add
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: /working_directory/my_add.cpython-310-x86_64-linux-gnu.so: undefined symbol: _Z3addii
On the other hand, if I built with
g++ -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) add.o my_add.cpp -o my_add$(python3-config --extension-suffix)
then everything worked fine.
I'd really appreciate it if anyone could help.