Building shared library which is executable and linkable using Cmake
5,998
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.
Related videos on Youtube
Author by
parasrish
Updated on September 18, 2022Comments
-
parasrish over 1 year
How to create an
executable shared-library
usingcmake
?Something like:
libtest.so :: linkable shared library
libtest.so :: executable too
Note: gcc/g++ options are known to achieve the same (https://unix.stackexchange.com/a/223411/152034). But the solution needs
cmake
way -
goldilocks over 5 yearsI don't think that bug report pertains exactly to this; PIC and PIE are not the same. Shared library code by default requires -fPIC, but it does not require -pie. Using
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? -
parasrish over 5 years1) I understand, pic and pie not the same. However, by the cmake discussions, seems they "do not have support for pie" directly as such. Now addressing the case, by introducing new flag (something like - position_independent_executable) or in some other way, is not being concluded. The reference, was to aware, about an open discussion in this front at cmake forum. 2) And after all, that has been tried, the posted one seems to be working (target_compile_options used with parameters as above).
-
FeRD over 5 yearsJust last week, it appears, the MR to resolve that discussion was merged, so in bleeding-edge / future cmake the
target_compile_options
/target_link_libraries
lines should no longer be necessary, as the relevant flags will be automatically added by thePOSITION_INDEPENDENT_CODE
property.