[CMake] Creating a library from subdirectories

Stephen Kelly steveire at gmail.com
Wed Nov 26 16:30:31 EST 2014


Chris Johnson wrote:

> * I do not want to use the add_library(component1 OBJECT
> ${component1_sources}) and add_library(toplevel
> $<TARGET_OBJECTS:component1> ... ) syntax if it can be avoided.

Is the constraint that you want a top-level something like 

  # All components:
  set(components component1 component2)

  foreach(comp ${components})
    add_subdirectory(${comp})
  endforeach()

  add_library(mylib dummy.c)
  target_link_libraries(mylib ${components})

  add_executable(other_target main.c)
  target_link_libraries(other_target mylib)

?

While at the same time not caring what type the components libraries are 
(OBJECT/STATIC etc)?

A solution for that is in CMake 3.1 by creating an INTERFACE library to hide 
the TARGET_OBJECTS expression:

 add_library(component1_objs OBJECT c1.c)

 add_library(component1 INTERFACE)
 target_sources(component1 INTERFACE
   $<TARGET_OBJECTS:component1_objs>
 )

There is a bug however, but I just pushed a fix for it after trying to 
extend your test case to use it:

 http://www.cmake.org/gitweb?p=stage/cmake.git;a=commitdiff;h=672f1001

An INTERFACE library also helps you avoid the dummy.c by not creating the 
intermediate archive at all, if that fits within what you're trying to 
achieve here:

  add_library(mylib INTERFACE)
  target_link_libraries(mylib INTERFACE ${components})

In the future it may be possible to link to OBJECT libraries directly 
without the INTERFACE library:

 http://public.kitware.com/Bug/view.php?id=14970

Another obvious solution, if it fits within what you're trying to achieve, 
is to avoid the OBJECT libraries instead:

 add_library(component1 INTERFACE)
 target_sources(component1 INTERFACE
   ${CMAKE_CURRENT_SOURCE_DIR}/c1.c
 )

This means that all binary consumers will compile their own version of each 
file, which you probably want to avoid.

Additionally, you do need to specify an absolute path or CMake issues a not-
informative-enough error. A second bug found from this thread, but which I 
haven't yet addressed (but should get done for 3.1 too).

Thanks,

Steve.




More information about the CMake mailing list