Using find_file with an indirected variable name

I’d expect this to work:

set(releaseLibName "lib${target}_${requiredVersion}_Rel")

find_file(${releaseLibName}
          NAMES lib${target}_${requiredVersion}.${EXTvar}
          PATHS ${MY_PATHS}
          DOC "${target} release library"
          NO_DEFAULT_PATH)

if (EXISTS ${${releaseLibName}})
    message("Found it!)
else()
    message("Not found")
endif()

…but it does not; even if the file I’m looking for definitely exists, ${${releaseLibName}} returns nothing.

In the other hand, this works fine:

find_file(ORDINARY_VARIABLE
          NAMES lib${target}_${requiredVersion}.${EXTvar}
          PATHS ${MY_PATHS}
          DOC "${target} release library"
          NO_DEFAULT_PATH)

if (EXISTS ${ORDINARY_VARIABLE})
    message("Found it!)
else()
    message("Not found")
endif()

Is it by design that find_file doesn’t work when the variable name is itself held in another variable (i.e. double indirection), of is there something subtly wrong with my syntax here?

What happens if you use some quotes?

set(releaseLibName "lib${target}_${requiredVersion}_Rel")

find_file("${releaseLibName}"
          NAMES lib${target}_${requiredVersion}.${EXTvar}
          PATHS ${MY_PATHS}
          DOC "${target} release library"
          NO_DEFAULT_PATH)

if (EXISTS "${${releaseLibName}}")
    message("Found it!")
else()
    message("Not found")
endif()

I’m fairly sure I tried that, but nothing I tried could get it to work with indirection.

What I did instead was to set CMP0125 to NEW so that I could use an ordinary non-cache variable to receive the path without a new cache variable being created. I could then copy this non-cache variable to another variable with an indirected name.

A lot of my problems in my wider code were caused by not realising that the default behaviour of find_file was to create a new cache variable, which then took precedence over non-cache variables. so in my example given above, even ORDINARY_VARIABLE was being created as a new cache variable without me realising.

Ah! Local variables always win over cache variables. The various policies involved here, including CMP0125, stopped these commands from mucking with the local variables. CMP0125 was particularly fun because it would nuke the local variable if the cache variable was of type UNINITIALIZED (basically, -DFOO=bar rather than -DFOO:STRING=bar on the command line) in the process of setting the cache type. If it already had a type, it would leave the local variable alone.

1 Like