phildue
phildue

Reputation: 31

Verify library is available before target_link_libraries in CMake Script

I have a large project consisting of several build targets with dependencies between them. The structure resembles sth like this:

Application <-- Library I <--- Library II
            <-- Library III <---|
            <-- Library IV

Multiple such Applications exist, which use shared code distributed across different libraries.

Within the project CMake is used to ensure correct include paths and linking among the various libraries.

The libraries are setup using add_library("Library II"), subsequently the other project get the dependencies using target_link_libraries("Library I" "Library II").

This works in most of the cases. However, sometimes certain dependencies are not found. I have the suspicion that in some cases "Library I" is not known. However, target_link_libraries() does not throw an error if a library is not known. The error will only appear when compiling / linking.

I would like to verify when running cmake already that all libraries are found. If sth is not known at that stage I would like to throw an error and inform the developer.

I tried using find_libraries() but in my understanding this looks for a certain file. However, in my case the file will only be compiled at compile stage, so the file does not exist when running cmake.

Upvotes: 3

Views: 2152

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 66288

Check the library target, not a file:

if(NOT TARGET library_2)
   message(SEND_ERROR "Attempt to link to non-existent library 'library_2'.")
endif()
target_link_libraries(library_1 library_2)

See also that question about checking the target.

Note, that this approach will work only when

add_library(library_2)

comes before

target_link_libraries(library_1 library_2)

CMake allows (and correctly processes) opposite order, but I find it to be good style to require direct order between a library creation and linking.

Upvotes: 3

Related Questions