[CMake] How to append arbitrary linker options?

Philip Lowman philip at yhbt.com
Fri Jan 30 13:24:54 EST 2009


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

>  Hello,
>
> 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)
    if(CMAKE_COMPILER_IS_GNUCC)
        set(new_link_flags "-Whatever")
        get_target_property(existing_link_flags ${_target} LINK_FLAGS)
        if(existing_link_flags)
            set(new_link_flags "${existing_link_flags} ${new_link_flags}")
        endif()
        set_target_properties(${_target} PROPERTIES LINK_FLAGS
${new_link_flags})
    endif()
endfunction()

add_executable(foo foo.cc)
add_my_mpi_ldflags(foo)

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


More information about the CMake mailing list