user1607549
user1607549

Reputation: 1569

CMake: Access variables across sub directories

I have a two sub directories from root on which one has the line:

 set(${LIBNAME}_publicheaders
     LocalizeResource.h
 )

I want to be able to access this variable from the other subdirectory. How can I do this?

Upvotes: 1

Views: 6444

Answers (2)

Fraser
Fraser

Reputation: 78320

@JoakimGebart's answer is probably the more common way to go about this. However, you can also use get_directory_property directly from within the second subdir to achieve what you're after.

I see that in your comment, you've used ${LIB_NAME}_publicheaders, but in your question you have ${LIBNAME}_publicheaders. This could be the cause of your problems, since the command should work like this:

get_directory_property(MyVar
    DIRECTORY ${CMAKE_SOURCE_DIR}/abc
    DEFINITION ${LIBNAME}_publicheaders)

However, there are a couple of provisos:

  1. This has to be called after setting the variable in the subdir. i.e. you'd have to ensure add_subdirectory(abc) was called before the add_subdirectory for the one where this will be used.
  2. If LIBNAME is also set inside the same subdir (abc), you'll need to retrieve the value for that first.

So, while this is probably a less common solution, it has the advantage that it doesn't "pollute" the global namespace with subdir-specific variables - this works from with a subdir referring to another subdir.

Upvotes: 6

Joakim Nohlgård
Joakim Nohlgård

Reputation: 1852

You can set the variable in the parent scope using the PARENT_SCOPE option to set()

Example:

set(${LIBNAME}_publicheaders
    LocalizeResource.h
    PARENT_SCOPE
)

See http://www.cmake.org/cmake/help/v2.8.10/cmake.html#command:set

This, however, means that the variable is available not only in the other subdirectory, but in any other subdirectories on the same level as well.

Upvotes: 4

Related Questions