[cmake-developers] Duplicated linking flags are removed when linking final executable

Brad King brad.king at kitware.com
Tue Mar 15 10:07:10 EDT 2016


On 03/15/2016 05:58 AM, Sergio Checa wrote:
> In this example, I only want libA and libB linked into the main
> executable iff their symbols are used somewhere in the linking
> chain (-as-needed).

This may work:

 add_library(A SHARED a.cpp)
 add_library(B SHARED b.cpp)
 add_library(L SHARED lib.cpp)
 target_link_libraries(main L
    -Wl,-as-needed A -Wl,-no-as-needed
    -Wl,-as-needed B -Wl,-no-as-needed
  )

The only thing that CMake guarantees about link line generation is
that it will start with the direct tll() arguments.  Additional
arguments may be appended to satisfy explicit and inferred
dependencies.

The problem with trying to do it through dependency propagation is
that all of CMake's logic for dependency propagation was designed
for libraries and not flags.  It has no idea how flags tie to the
libraries or how multiple arguments should be grouped.  While your
patch may fix your particular use case it may also change existing
behavior for other projects in ways we cannot anticipate.

If you search the list archives you'll find discussion about the
possibility of defining a LINK_ITEMS target property that specifies
how a library should appear on the link line as a group of items
that are always kept together.  This would allow groups as above.
However, the discussion never reached a conclusion about the design.

Another approach would be to have a first-class feature added to
support -as-needed behavior activated by a target property.

-Brad


More information about the cmake-developers mailing list