NOTE: First information regarding this is, there is seemingly an open issue related to cmake. Therefore this can be considered as an indirect solution to achieve the same.
Now follow the illustration using cmake
.
test.cpp
#include <stdio.h>
void sayHello (char *tag) {
printf("%s: Hello!\n", tag);
}
int main (int argc, char *argv[]) {
sayHello(argv[0]);
return 0;
}
ttest/test_test.cpp
#include <stdio.h>
extern void sayHello (char*);
int main (int argc, char *argv[]) {
printf("\nNow Inside test-test !\n");
sayHello(argv[0]);
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(pie_test)
#shared-lib as executable
add_library(${PROJECT_NAME} SHARED
test.cpp
)
target_compile_options(${PROJECT_NAME} PUBLIC "-pie")
target_link_libraries(${PROJECT_NAME} "-pie -Wl,-E")
set_property(TARGET ${PROJECT_NAME} PROPERTY POSITION_INDEPENDENT_CODE 1)
#executable linking to the executable-shared-library
add_executable(test_test
ttest/test_test.cpp
)
target_link_libraries(test_test pie_test)
set_property(TARGET test_test PROPERTY POSITION_INDEPENDENT_CODE 1)
build.sh
#!/bin/bash
rm -rf build
mkdir build
cd build
cmake .. #--debug-output
make VERBOSE=1
echo "Done!"
echo ""
Reference for gcc-options here.
PROPERTY POSITION_INDEPENDENT_CODE
should only do the former, or, as the last poster there says, it should do it for executables -- and a shared library in a cmake context is not an executable. But you can still add -pie if you like. Did you try using target_compile_options? – goldilocks Nov 02 '18 at 12:29target_compile_options
/target_link_libraries
lines should no longer be necessary, as the relevant flags will be automatically added by thePOSITION_INDEPENDENT_CODE
property. – FeRD Nov 22 '18 at 07:16