Cannot build pybind11/libtorch code with cmake

Hi,

My play.cpp code is like this:

#include "pybind11/pybind11.h"
#include <torch/torch.h>
#include <torch/extension.h>

torch::Tensor get_ten() {
    return torch::ones({3, 4});
}


PYBIND11_MODULE(play, m) {
    m.doc() = "load image with c++";
    m.def("get_ten", &get_ten, "get single image float32 array");
}

My CMakeLists.txt file is like this:

cmake_minimum_required (VERSION 3.0 FATAL_ERROR)
project (play)

set (CMAKE_PREFIX_PATH /root/build/libtorch)
find_package(Torch REQUIRED)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
message (${CMAKE_CXX_FLAGS})

list(APPEND LIGHTSTEP_LINK_LIBRARY glog pthread )

add_subdirectory(pybind11)
pybind11_add_module(play SHARED play.cpp)
target_link_libraries(play PRIVATE ${TORCH_LIBRARIES} ${LIGHTSTEP_LINK_LIBRARY})
set_property (TARGET play PROPERTY CXX_STANDARD 14)

I compile it like this:

mkdir -p build && cd build
cmake .. && make

The compile process succeed, but when I import it, there is an error:

import torch
import play
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: /root/repo/play/build/play.cpython-36m-x86_64-linux-gnu.so: undefined symbol: _ZN3c105ErrorC1ENS_14SourceLocationENSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE

I am using pytorch1.6 installed from cuda pytorch channel, and libtorch downloaed from the link: https://pytorch.org/get-started/locally/. My local cuda versin is 10.1.243, and in my conda environment, I use cudatoolkit of version 10.1.243.

What is the problem here please ?

Hi @coincheung,

You should be able to just define -D_GLIBCXX_USE_CXX11_ABI=0 for your library and you should be fine (in CMake add the line add_definitions(-D_GLIBCXX_USE_CXX11_ABI=0)).

More context: the pytorch core library and your extension must be built with the same CXX11 API settings. This used to be _GLIBCXX_USE_CXX11_ABI=1 for older versions ans is =0 now for newer ones. I thought that for a while it was possible to build extensions without setting this flag at all, but it seems it’s explicitly required again.