[CMake] How to append arbitrary linker options?

Brad King brad.king at kitware.com
Fri Jan 30 14:42:50 EST 2009


Bartlett, Roscoe A 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?

There is currently no explicit feature for this.  You can hack it for
Makefile generators by writing

  set(CMAKE_CXX_LINK_EXECUTABLE
    "${CMAKE_CXX_LINK_EXECUTABLE} ${NASTY_FLAGS}")

and similarly for the other languages.  There is no equivalent for
Visual Studio or Xcode though.

Another (hack) approach is to convince CMake's link dependency analysis
to put your flags at the end using a helper target:

  add_library(last STATIC dummy.c)
  target_link_libraries(last ${NASTY_FLAGS})
  # ... link every target to 'last'
  add_library(mylib ...)
  target_link_libraries(mylib last)

This will guarantee that 'last' comes after all other targets on link
lines and that ${NASTY_FLAGS} comes after that.

I suggest doing the work to find the libraries and specify them
properly.  Blindly passing flags from foo-config scripts could lead to
trouble, especially when using multiple such flag sets.  For example,
consider when foo-config returns

  -L/path/to/foo/lib -lfoo

and bar-config returns

  -L/path/to/bar/lib -lbar

but /path/to/bar/lib contains a (wrong) version of libfoo.  If these two
sets of flags get appended in the wrong order the wrong foo will be
found.  On the other hand if the outputs of foo-config and bar-config
are parsed and used to find the corresponding libraries with full paths,
CMake will compute a safe link line for you.

-Brad



More information about the CMake mailing list