Friday, July 29, 2022

[SOLVED] Cmake using git-submodule inside a shared library

Issue

I try to add the library spdlog to a dll (.so file). The spdlog is just a git submodule from the spdlog library. Looking at the documentation, it's recommended to use it as a static library. So i think i have a problem trying to compile it inside a .so file.

To get a clear view of what i'm doing, here is a pic of my system: enter image description here

My root CMakeLists.txt is :

cmake_minimum_required(VERSION 3.23)

# set the project name
project(Test VERSION "0.1.0" LANGUAGES CXX)

configure_file(config/config.h.in config.h)

# specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++17 -O3")

# Set location for .so files
set(CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}")

# Set location for executables
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)

add_subdirectory(Engine)
list(APPEND EXTRA_LIBS Engine)

add_subdirectory(Game)

target_link_libraries(Test PUBLIC ${EXTRA_LIBS})

target_include_directories(Test PUBLIC
                           "${PROJECT_BINARY_DIR}"
                           )

And inside the Engine folder:

message(STATUS "BUILD Engine shared library File")

add_subdirectory(spdlog)
add_library(Engine SHARED Log.cpp Log.h)
target_include_directories(Engine
          INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
          )

target_link_libraries(Engine
spdlog
)
target_include_directories(Engine
          INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/spdlog/include
          )

Inside the Game (not relevant at my opinion)

message(STATUS "BUILD .exe File")
# add the executable
add_executable(Test main.cpp)

But currently, if i try to use the spdlog inside my Log file, i have this cryptic error:

[build] /usr/bin/ld: spdlog/libspdlogd.a(spdlog.cpp.o): relocation R_X86_64_TPOFF32 against `_ZGVZN6spdlog7details2os9thread_idEvE3tid' can not be used when making a shared object; recompile with -fPIC

Does anyone have an idea?


Solution

Thanks to fabian in the comments, I add

set(CMAKE_POSITION_INDEPENDENT_CODE 1)

Just before adding the spdlog subdirectory and it just works fine.



Answered By - miyoku
Answer Checked By - Candace Johnson (WPSolving Volunteer)