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.