CMake Position Independent Code

Certain projects with legacy build systems like Make or Autotools or in general may specify to build with flags like “-fPIC” for position independent code (PIC) on Linux systems. Consider not forcing these flags in CMake projects if there isn’t a specific known need, to let users and consuming projects decide whether they need PIC or not. When PIC is needed, do like:

if(...)
  include(CheckPIESupported)

  check_pie_supported()

  set(CMAKE_POSITION_INDEPENDENT_CODE true)
endif()

The check_pie_supported module checks whether the compiler supports PIE and should be run before setting target property POSITION_INDEPENDENT_CODE.

When PIC is enabled with certain platforms like Intel oneAPI on Linux, linker errors may result like

relocation R_X86_64_32 against `.rodata.str1.1’ can not be used when making a PIE object

where the solution is to disable PIC – or simply do not enable it by default in the CMake project as we suggested above.