'Linking issues "relocation against `g_GIT_SHA1' in read-only section `.text'" and "undefined reference to `g_GIT_SHA1'"
I was trying to follow the procedure in this answer https://stackoverflow.com/a/4318642 with a test:
CMakeFile.txt
#cmake version setup
cmake_minimum_required(VERSION 3.1)
project(Checksumtest VERSION 1.0
LANGUAGES CXX
)
if(NOT CMAKE_CXX_COMPILER)
set(CMAKE_CXX_COMPILER "g++")
endif()
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}")
include(GetGitRevisionDescription)
get_git_head_revision(GIT_REFSPEC GIT_SHA1)
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/GitSHA1.cpp.in" "${CMAKE_CURRENT_BINARY_DIR}/GitSHA1.cpp" @ONLY)
set(LIB_LIST "${CMAKE_CURRENT_BINARY_DIR}/GitSHA1.cpp" "${PROJECT_SOURCE_DIR}/include/checksum/GitSHA1.h")
add_library(checksum SHARED ${LIB_LIST})
target_include_directories(checksum PUBLIC "${PROJECT_SOURCE_DIR}/include/checksum")
#target_compile_features(checksum PUBLIC cxx_std_11)
target_compile_options(checksum PRIVATE -O3 -fPIC)
add_executable(test_checksum test.cpp)
target_compile_features(test_checksum PRIVATE cxx_std_11)
target_compile_options(test_checksum PRIVATE -O3)
target_link_libraries(test_checksum PRIVATE checksum)
target_include_directories(test_checksum PRIVATE "${PROJECT_SOURCE_DIR}/include/checksum")
GitSHA1.h
extern const char g_GIT_SHA1[];
GitSHA1.cpp.in
#define GIT_SHA1 "@GIT_SHA1@"
const char g_GIT_SHA1[] = GIT_SHA1;
test.cpp
#include <iostream>
#include "GitSHA1.h"
int main(int argc,char *argv[]) {
std::cout<<"Checksum"<<" "<<g_GIT_SHA1<<std::endl;
}
I tried several options but I always get an error like this:
FAILED: checksum/test_checksum
: && /usr/bin/c++ -g -rdynamic checksum/CMakeFiles/test_checksum.dir/test.cpp.o -o checksum/test_checksum -Wl,-rpath,/home/francesco/Simula/b-EdgeCover/cmake-build-debug/checksum checksum/libchecksum.so && :
/usr/bin/ld: checksum/CMakeFiles/test_checksum.dir/test.cpp.o: warning: relocation against `g_GIT_SHA1' in read-only section `.text.startup'
/usr/bin/ld: checksum/CMakeFiles/test_checksum.dir/test.cpp.o: in function `std::char_traits<char>::length(char const*)':
/usr/include/c++/11/bits/char_traits.h:371: undefined reference to `g_GIT_SHA1'
/usr/bin/ld: warning: creating DT_TEXTREL in a PIE
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
What can I do?
Edit 1: I tried with the fixes findable with some researches (i.e. relocation against xxx in read-only section '.text' - wrong compiler or linux setup in SUSE?), but I cannot solve it in any way. Anyone did have a similar situation?
Solution 1:[1]
Add to GitSHA1.cpp:
#include GitSHA1.h
For the rationale check: https://stackoverflow.com/a/14894897/7268445
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Bart |