Friday, June 3, 2022

[SOLVED] Test if required package found

Issue

Let's say I need to get a package PX.

find_package(PX REQUIRED)
if(PX_FOUND)
    target_link_libraries(foo PX::lib)
endif()

Since I marked the package as REQUIRED, is the test necessary ? Is there any situation where I won't be able to link PX ?


Solution

Since I marked the package as REQUIRED, is the test necessary?

No, it is not necessary. If no compatible module or config file on the search path sets <PkgName>_FOUND, then find_package(PkgName REQUIRED) will kill the configure step right then and there. It's a fatal error. Checking the variable is pointless. You can safely write:

find_package(PX REQUIRED)
target_link_libraries(foo PRIVATE PX::lib)

Don't forget to set a visibility specifier when using target_link_libraries.



Answered By - Alex Reinking
Answer Checked By - Terry (WPSolving Volunteer)