Luca
Luca

Reputation: 11016

Append to target link libraries

Currently, in my CMake file, I do the following based on whether OpenMP is found or not:

if(OpenMP_CXX_FOUND)
    target_link_libraries(myapp PRIVATE lib_1 lib_2 OpenMP::OpenMP_CXX PUBLIC io_lib)
else(OpenMP_CXX_FOUND)
    target_link_libraries(myapp PRIVATE lib_1 lib_2 PUBLIC io_lib)

Perhaps, I am being picky here but this looks a bit ugly. I am wondering if there is a canonical way to do this which does not result in an ugly config. Perhaps, something like appending to the list of libs might be cleaner, but I could not figure out how to access the PRIVATE interface.

Upvotes: 4

Views: 3792

Answers (1)

Kevin
Kevin

Reputation: 18396

A couple variations:

Instead, you can just conditionally append the OpenMP::OpenMP_CXX target:

target_link_libraries(myapp PRIVATE lib_1 lib_2 PUBLIC io_lib)
if(OpenMP_CXX_FOUND)
    target_link_libraries(myapp PRIVATE OpenMP::OpenMP_CXX)
endif()

as consecutive calls to target_link_libraries for the same target will append items in the order called.

Or, you can cut this logic down to a one-liner, using a conditional generator expression:

target_link_libraries(myapp 
    PRIVATE lib_1 lib_2 $<IF:${OpenMP_CXX_FOUND},OpenMP::OpenMP_CXX,> 
    PUBLIC io_lib
)

Upvotes: 6

Related Questions