[CMake] Advice on how to remove duplicated code for object and interface library setup

Stephen McDowell sjm324 at cornell.edu
Thu Mar 15 22:17:43 EDT 2018


I am trying to obey modern CMake target-based practices, with a twist that everything is available as an OBJECT library if desired.  I have this working and can explain why if desired, but I feel it is extraneous for this question.  What I create:

- mylib <- the main library
    - mylib_obj <- contains all of the actual objects for the library (OBJECT library)
    - mylib_interface <- linked with mylib

So it looks like this:

    add_library(mylib_obj OBJECT "")
    add_library(mylib_interface INTERFACE)

Based on various options / settings, target_sources(mylib_obj) will be set and all of the various compiler operations etc.  At the end, I have

    # MYLIB_LIBRARY_TYPE is either SHARED or STATIC
    add_library(mylib ${MYLIB_LIBRARY_TYPE} $<TARGET_OBJECTS:mylib_obj>)
    target_link_libraries(mylib mylib_interface)

This works nicely, but internally I have to do the same operations for both mylib_obj and mylib_interface.

    target_include_directories(mylib_obj PUBLIC ${SomeLib_INCLUDE_DIRS})
    target_include_directories(mylib_interface INTERFACE ${SomeLib_INCLUDE_DIRS})
    target_link_libraries(mylib_interface INTERFACE ${SomeLib_LIBRARIES})

Without mylib_interface, I cannot include the future linking information as well as include / compiler directive information will not be propagated with target_link_libraries(something mylib).  But mylib_obj also needs include information, etc.  But I can’t do

    target_link_libraries(mylib_obj mylib_interface)

because mylib_obj is an object library.

Is there a way to avoid having to set the same thing for both mylib_obj and mylib_interface given the requirement that mylib_obj is intended to house all of the actual objects?

Thank you for any guidance, I’m sorry if this question doesn’t make much sense.  I’m trying to unlearn all of my outdated self-taught CMake!

-Stephen

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://cmake.org/pipermail/cmake/attachments/20180315/7ccba932/attachment.html>


More information about the CMake mailing list