[CMake] Scope of find_package inside a function block

Michael Wild themiwi at gmail.com
Fri Sep 23 00:20:54 EDT 2011


On Thu 22 Sep 2011 11:17:14 PM CEST, Lori Pritchett-Sheats wrote:
> I was wondering what the scope of the variables set in a FindXXX.cmake
> file is and does find_package_handle_standard_args change that scope.
>
> For example, I create a FindBar.cmake file that sets Bar_INCLUDE_DIR,
> Bar_LIBRARY, Bar_INCLUDE_DIRS and Bar_LIBRARIES, and calls
> find_package_handle_standard_args to set Bar_FOUND correctly if
> Bar_INCLUDE_DIRS and Bar_LIBRARIES is set. If I call find_package(Bar)
> inside a function-endfunction block, are the variables scoped outside
> the function block?
>
> I have a simple test case and I'm seeing strange results where some of
> the Bar_* variables are defined outside the function block. It's very
> strange. I'm wondering if my find_package_handle_standard_args call
> affects the variable scope, because  in my simple test case,
> Bar_FOUND, Bar_INCLUDE_DIRS and Bar_LIBRARIES are not set outside the
> function block, but Bar_INCLUDE_DIR and Bar_LIBRARY are.
>
> Thanks.
>

Only the cached variables will be visible outside the function scope,
all others not. Usually a FindXXX.cmake module looks like this:

find_path(XXX_INCLUDE_DIR xxx.h)
find_library(XXX_xxx_LIBRARY xxx)
find_library(XXX_yyy_LIBRARY yyy)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(XXX DEFAULT_MSG
  XXX_INCLUDE_DIR XXX_xxx_LIBRARY XXX_yyy_LIBRARY)
if(XXX_FOUND)
  set(XXX_INCLUDE_DIRS ${XXX_INCLUDE_DIR})
  set(XXX_LIBRARIES ${XXX_xxx_LIBRARY} ${XXX_yyy_LIBRARY})
endif()

Now, the find_path() and find_library() calls store their results in the
cache, so the values are global, but all the other variables, such as
XXX_FOUND, XXX_INCLUDE_DIRS and XXX_LIBRARIES (notice the plural of the
latter two) are not cached, and thus subject to the function scope.
Also, their value will not be propagated upwards in the directory tree.

BTW: This is one of the few exceptions where I think that macros are
useful, because they allow you to call find_package() without knowing
all the variable that are being set.

HTH

Michael


More information about the CMake mailing list