I am facing some issues when trying to compile a shared library using CMake on Ubuntu (16.04) and linking it to an executable compiled with CMake on CentOS (6.8).
The first CMakeLists.txt to create the library looks like this:
cmake_minimum_required(VERSION 3.0)
project(MyLibrary)
file(GLOB ${SOURCES} SOURCES "src/*.cpp")
include_directories(${PROJECT_SRC_DIR}/include)
set(CMAKE_CXX_FLAGS "-std=c++11")
add_library(${PROJECT_NAME} SHARED ${SOURCES})
which will create libMyLibrary.so
The second CMakeLists.txt is:
cmake_minimum_required(VERSION 3.0)
project(MyApp)
set(MY_LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../build)
include_directories(${MY_LIB_DIR}/include)
set(CMAKE_CXX_FLAGS "-std=c++98")
add_executable(${PROJECT_NAME} "main.cpp")
target_link_libraries(${PROJECT_NAME} ${CMAKE_CURRENT_SOURCE_DIR}/../build/libMyLibrary.so)
Note that the library was built in build
directory, while the final executable MyApp
is built in a different folder. On Ubuntu this combination works, while generating the library on Ubuntu and compiling only the second part on CentOS throws undefined reference
for every function defined in C++11 and not defined in the C++98 standard. In fact, this was initially the reason why I did this: to build the library (containing C++11) with a more recent version of g++, and link it to the executable on CentOS, where an older version, not supporting the standard, is available (I have no root access on CentOS).
I would like to know if what I am trying to do is even possible, and, if yes, what am I missing.
EDIT After the answer of Matthieu Brucher, I added the flag -D_GLIBCXX_USE_CXX11_ABI=0
to the first CMakeLists.txt file, in addition to the -std=c++11
flag. This removed undefined reference
errors, but stil keeps the following:
undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::basic_string<char,std::char_traits<char>,std::allocator<char> >&&)@GLIBCXX_3.4.14'
undefined reference to `std::basic_ios<char, std::char_traits<char>>::operator bool() const@GLIBCXX_3.4.21'
undefined reference to `std::random_device::_M_getval()@GLIBCXX_3.4.18'
undefined reference to `std::random_device::_M_fini()@GLIBCXX_3.4.18'
undefined reference to `std::random_device::_M_init(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)@GLIBCXX_3.4.18'
The main issue with this is that the c++11 version has a different abi. If you want to compile c++11 with the old abi, add the macro _GLIBCXX_USE_CXX11_ABI=0
.
Then the undefined references should be solved.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.