-2

I have an issue when linking a simple main program with a shared library that has a function taking in a pybind11::object as an argument. (only external dependancy is pybind11, I am using gcc version 13.2.0, python version 3.11.4)

pymodule.h:

#ifndef PYMODULE_H
#define PYMODULE_H
#include <pybind11/embed.h>

pybind11::object foo();
void foo(pybind11::object);
int bar();

#endif

pymodule.cpp:

#include "pymodule.h"

pybind11::object foo(){
    return pybind11::object();
}

void foo(pybind11::object object)
{
    pybind11::print(object);
}

int bar()
{
    return 42;
}

main.cpp:

#include <iostream>
#include <pybind11/embed.h>

#include "pymodule.h"

int main()
{
    pybind11::scoped_interpreter guard{};
   
    
    //pybind11::object obj = foo(); //does not compile
    foo(pybind11::none()); // does not compile
    int c = bar(); //compiles

    std::cout << "Hello World:" << c << "\n";

    return 0;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)
project(sandbox LANGUAGES CXX)

set(CXX_STANDARD_REQUIRED true)

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_subdirectory(extern/pybind11)

add_library(mylib SHARED #STATIC
pymodule.cpp)


target_link_libraries(mylib PUBLIC pybind11::embed)

add_executable(main main.cpp)

target_link_libraries(main PUBLIC mylib)

When i call any function that returns or takes in a pybind11::object as argument i get the following error

compile output:

[ 50%] Built target mylib
[ 50%] Linking CXX shared module pymodule.cpython-311-x86_64-linux-gnu.so
[ 66%] Linking CXX executable main
/usr/bin/ld: CMakeFiles/main.dir/main.cpp.o: in function `main':
main.cpp:(.text+0x302): undefined reference to `foo()'
/usr/bin/ld: main.cpp:(.text+0x32d): undefined reference to `foo(pybind11::object)'
collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/main.dir/build.make:99: main] Error 1
make[1]: *** [CMakeFiles/Makefile2:156: CMakeFiles/main.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[ 83%] Built target pymodule
make: *** [Makefile:91: all] Error 2

However, when i try to link it as a static lib it compiles fine. Is there a problem with exporting symbols in shared libs that use pybind11::object or is this a different problem entirely?

Lman96
  • 1
  • 2
  • 3
    [tag:C] C is distinct from C++ and it should not be combined with the C++ tag without a specific reason. – 273K Aug 31 '23 at 15:05
  • Thanks for the feedback, however I added the C tag because of the CPython implementation used by pybind11, and i suspected the linking problem had something to do with that. (the one i am using is CPython) – Lman96 Sep 01 '23 at 07:15
  • I am mistaken, the linking error cannot be anything regarding to the C-API. I'll remove the tag. – Lman96 Sep 01 '23 at 07:59

0 Answers0