How to set -dynamic-linker from the outside?

By trial and error, I found out that my current (yeah, it should be -rpath rather than --rpath…):

add_link_options(
    LINKER:-rpath,<rpath-path>
    LINKER:-dynamic-linker,<dynamic-linker-path>
)

could be replaced in a few ways revolving around various variables.


As of now, I’m going to use:

LDFLAGS="${LDFLAGS} -Wl,-dynamic-linker,<dynamic-linker-path>"
CMAKE_BUILD_RPATH=<rpath-path>

LDFLAGS is an environment variable while CMAKE_BUILD_RPATH is provided as -D<var>=<value> command-line argument do cmake configuration call.

However, this particular choice is dictated mostly by the setup we have right now. In a different setup perhaps a different approach would be better.


For completeness, I will list here variables that seem to be related to the topic:

TBH, I’m somewhat lost in all those options… However, I will share some thoughts on them I have after spending significant time on this topic:

  1. I don’t like setting environment variable LDFLAGS (because I don’t like dependency on environment variables in general).
    – However, it does save me from setting three variables: CMAKE_EXE_LINKER_FLAGS_INIT, CMAKE_MODULE_LINKER_FLAGS_INIT, and CMAKE_SHARED_LINKER_FLAGS_INIT.
    – If using a CMAKE_TOOLCHAIN_FILE, as already suggested by @fenrir, maybe I would opt for separate variables, but having to pass them all via -D<var>=<value> seems a bit too verbose.
    – We use LDFLAGS already anyway for other flags, I’m not sure how it would behave if I would separately set the CMAKE_<TYPE>_LINKER_FLAGS_INIT variables but I expect it would overwrite everything that would be taken from LDFLAGS which is not desired.
  2. I don’t know if it is better to set rpath by linker flags or by CMake variables.
    – I assume CMake variables are better since it will lead to a cleaner situation from CMake’s point of view and avoid conflicts.
    – And also they are more fine-grained. It is easier to have a single variable with single path of clear purpose rather than append to a cumulative options variable.
  3. The add_link_options has a nice LINKER: mode that covers specifics of the compiler (for example, -Wl for GCC and -Xlinker for Clang).
    – When setting the variables manually within CMake you can still use CMAKE_LANG_LINKER_WRAPPER_FLAG and CMAKE_LANG_LINKER_WRAPPER_FLAG_SEP. Probably non-trivial and verbose to use it correctly, but at least possible.
    – However, when setting them from the outside (which is the whole point of setting them in the first place) you now must cover the compiler specifics on your own and the same settings will not work with both GCC and Clang.