title: cmake: In which order do I have to specify TARGET_LINK_LIBRARIES
body: <p>I am struggling again and again with linker problems since one has to specify all libraries within TARGET_LINK_LIBRARIES in the correct order. But how can I determine this order? <strong>Example:</strong></p>
  
  <p>I have the following libraries</p>
  
  <pre><code>libA depends on boost
  libB depends on postgresql and libA (and therefore on boost)
  myTarget uses libA, libB and boost directly (and through libB depends on postgresql)
  </code></pre>
  
  <p>Since all required libaries are only linked if an executable is created I have to specifiy all libraries when linking myTarget (the final executable):</p>
  
  <pre><code>TARGET_LINK_LIBRARIES(${ApplicationName}  
  
  libboost_program_options.a 
  libboost_system.a 
  libboost_filesystem.a 
  libboost_date_time.a 
  libboost_regex.a 
  
  # Should include all boost libraries but strangely some libs (the ones above)
  # need to be specified "by hand"???
  ${Boost_LIBRARIES} 
  
  # PostgreSQL stuff
  libpq.a
  libsoci_core.a
  libsoci_postgresql.a
  libpq.so
  
  # My libs
  libB.a
  libA.a
  
  ${CMAKE_THREAD_LIBS_INIT} # pthreads, needed by boost
  ${CMAKE_DL_LIBS} # For libdl.so etc.
  ) 
  </code></pre>
  
  <p>Since I am linking boost static my CMakeLists.txt also contains</p>
  
  <pre><code>SET(Boost_USE_STATIC_LIBS ON) 
  </code></pre>
  
  <p>However, I still get linking errors such as "undefined references to boost::re_detail::perl_matcher or boost::date_time::month_formatter"</p>
  
  <p>This is really annoying, I am changing the lib ordering and some undefined references disappear but new undefined references appear.</p>
  
  <p><strong>How can I identify the correct ordering?!</strong></p>
  
  <hr>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I solved the problem above by drawing respectively identifying all dependencies between the libs and ordering them appropriately (therefore libboost_log.a has been added):</p>
  
  <pre><code>TARGET_LINK_LIBRARIES(${ApplicationName}  
  libB.a
  libA.a
  
  # PostgreSQL stuff
  libpq.a
  libsoci_core.a
  libsoci_postgresql.a
  libpq.so
  
  # Boost
  libboost_program_options.a 
  libboost_system.a 
  libboost_log.a 
  libboost_filesystem.a 
  libboost_date_time.a 
  libboost_regex.a 
  # Should include all boost libraries but strangely some libs (the ones above)
  # need to be specified "by hand"???
  ${Boost_LIBRARIES} 
  
  # Lowlevel needed by boost
  ${CMAKE_THREAD_LIBS_INIT} # pthreads, needed by boost
  ${CMAKE_DL_LIBS} # For libdl.so etc.
  ) 
  </code></pre>
  
  <p>So the ordering is top down. Top is the executable, followed by directly used libraries. Further dependencies follow and finally at the end one has to add low level dependencies (used by boost).</p>