title: C/cmake - how to add a linker flag to an (unused) library when the library is specified in TARGET_LINK_LIBRARIES?
body: <p>In the root directory of my project, I have a subdirectory for <code>my_lib</code> and another for <code>my_app</code>.
  The library <code>my_lib</code> defines tables that populates a section defined by the linker, these tables are not used directly by <code>my_app</code>, so this library is not linked.</p>
  
  <p>To force my_lib to be linked I added the flag --whole-archive as described <a href="https://stackoverflow.com/questions/14116420/how-to-force-gcc-to-link-an-unused-static-library">here.</a></p>
  
  <p>And it works!</p>
  
  <p>In the CMakelist.txt of the root directory I have the following:</p>
  
  <pre><code>SET(CMAKE_EXE_LINKER_FLAGS "-mmcu=cc430f6137 -Wl,--gc-sections -Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive")
  ADD_SUBDIRECTORY(my_lib)
  </code></pre>
  
  <p>In the <code>CMakelist.txt</code> of <code>my_lib</code> I have:</p>
  
  <pre><code>ADD_LIBRARY(MY_LIB
      my_lib.c
  )
  TARGET_LINK_LIBRARIES(MY_LIB)
  </code></pre>
  
  <p>In the <code>CMakelist.txt</code> of <code>my_app</code> I have:</p>
  
  <pre><code>ADD_EXECUTABLE(my_app my_app.c)
  TARGET_LINK_LIBRARIES(my_app MY_LIB)
  </code></pre>
  
  <p>My problem is I just want to use this flag (<code>--whole-archive</code>) if <code>MY_LIB</code> is specified in the <code>TARGET_LINK_LIBRARIES</code> in <code>CMakelist.txt</code> of <code>my_app</code>.</p>
  
  <p>If the the last line <code>TARGET_LINK_LIBRARIES(my_app MY_LIB)</code> is not there, I don't want to add <code>"-Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive"</code> in the <code>CMAKE_EXE_LINKER_FLAGS</code>.</p>
  
  <p>I tried to remove this flag from the CMakelist.txt in root and add the following into the <code>CMakelist.txt</code> in <code>my_lib</code> subdirectory:</p>
  
  <pre><code>SET_TARGET_PROPERTIES(MY_LIB PROPERTIES CMAKE_EXE_LINKER_FLAGS "-Wl,--whole-archive -lMY_LIB -Wl,--no-whole-archive")
  </code></pre>
  
  <p>But this does not work.</p>
  
  <p>How can I do this?</p>