[CMake] How to append arbitrary linker options?

Bartlett, Roscoe A rabartl at sandia.gov
Sun Feb 1 17:45:52 EST 2009

Setting set_target_properties(foo PROPERTIES LINK_FLAGS ...)  does not work.  The other libraries just come after these flags.

- Ross

From: philiplowman at gmail.com [mailto:philiplowman at gmail.com] On Behalf Of Philip Lowman
Sent: Friday, January 30, 2009 11:25 AM
To: Bartlett, Roscoe A
Cc: cmake at cmake.org; Perschbacher, Brent M
Subject: Re: [CMake] How to append arbitrary linker options?

On Fri, Jan 30, 2009 at 12:56 PM, Bartlett, Roscoe A <rabartl at sandia.gov<mailto:rabartl at sandia.gov>> wrote:

I would like to be able to append arbitrary linker options to the end of my link lines on Unix/Linux systems.  However, the options set in the CMAKE_EXE_LINKER_FLAGS variable are listed *before* all of the libraries that CMake knows about.  I need to be able to append a bunch of nasty options like Fortran libraries, MPI libraries (in some nasty cases) and other libraries that must come after all other libraries.

The problem is that while I could carefully list the libraries that need to be appended and I could use find_library(...) to get them correctly I may just have a glob of libraries and other linker options that someone gives me and I just want to apply them without having to parse everything out.

Is there some way to force CMake on Unix/Linux systems to append arbitrary linker options?

You can use set_target_properties(foo PROPERTIES LINK_FLAGS ...) on your targets. The LINK_FLAGS property will not contain CMAKE_EXE_LINKER_FLAGS, it's merely for special flags to be appended to linking a particular target.  If you need to apply the same linking flags to many targets you can create a function() to ease your pain.

Also, be aware if you set the LINK_FLAGS property twice, the second call will overwrite the first. If you need to append to LINK_FLAGS (lets say you want one function to add fortran linking options and the other for MPI) you must first use get_target_property() and check to see if the property existed, and then append to it.

function(add_my_mpi_ldflags _target)
        set(new_link_flags "-Whatever")
        get_target_property(existing_link_flags ${_target} LINK_FLAGS)
            set(new_link_flags "${existing_link_flags} ${new_link_flags}")
        set_target_properties(${_target} PROPERTIES LINK_FLAGS ${new_link_flags})

add_executable(foo foo.cc)

Philip Lowman
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.cmake.org/pipermail/cmake/attachments/20090201/6e833304/attachment.htm>

More information about the CMake mailing list