diff --git a/cmake/modules/AddCompilerFlags.cmake b/cmake/modules/AddCompilerFlags.cmake --- a/cmake/modules/AddCompilerFlags.cmake +++ b/cmake/modules/AddCompilerFlags.cmake @@ -33,3 +33,13 @@ string(REGEX REPLACE "${f}( |^)" "" CMAKE_C_FLAGS ${CMAKE_C_FLAGS}) endforeach() endmacro() + +# Note that CMake does not provide any facility to check that a linker flag is +# supported by the compiler, but most linker will just drop any unsupported flag +# (eventually with a warning). +function(add_linker_flag) + foreach(f ${ARGN}) + string(APPEND CMAKE_EXE_LINKER_FLAGS " ${f}") + endforeach() + set(CMAKE_EXE_LINKER_FLAGS ${CMAKE_EXE_LINKER_FLAGS} PARENT_SCOPE) +endfunction() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -24,6 +24,15 @@ # Enable warning include(AddCompilerFlags) +# CMake provides the POSITION_INDEPENDENT_CODE property to set PIC/PIE. +# Unfortunately setting the -pie linker flag this way required CMake >= 3.14, +# which is not widely distributed at the time of writing. +# FIXME: use the POSITION_INDEPENDENT_CODE property instead +if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "Windows") + add_compiler_flag(-fPIC -fPIE) + add_linker_flag(-pie) +endif() + add_c_compiler_flag(-Wnested-externs -Wstrict-prototypes) add_compiler_flag( -Wall