Conditionally setting CMAKE_EXE_LINKER_FLAGS based on linker type is not documented/possible
On Windows, different C/C++ compilers might be used, e.g. Intel, PGI, or gcc via mingw64. The corresponding linker can be different for each (MSVC's link.exe vs UNIX's ld), and hence the allowed linker flags are different. Searching through the docs, CMake source code, and GitHub I couldn't find a unique pattern to write the condition for setting linker flags based on the linker type.
In particular, trying to detect MSVC's linker is quite tricky. if (MSVC)
is false when using PGI, if (WIN32)
is true when using mingw64 from the command prompt. Which other condition could I use to detect whether MSVC's link.exe
is used?
I found the undocumented internal variable CMAKE_LINKER
which contains the full path to the linker, e.g. /usr/bin/ld
or C:/msys64/mingw64/bin/ld.exe
or C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/VC/Tools/MSVC/14.12.25827/bin/Hostx64/x64/link.exe
or C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/link.exe
. So theoretically I could do:
get_filename_component(LINKER_FILENAME ${CMAKE_LINKER} NAME)
if (LINKER_FILENAME STREQUAL link.exe)
...
elseif (LINKER_FILENAME STREQUAL ld OR LINKER_FILENAME STREQUAL ld.exe)
...
endif()
But given it's an internal variable, this can't be the right way.
Is this a missing feature or is the documentation just a bit incomplete?