Home CMake <PROJECT-NAME>_SOURCE_DIR Variable Scope
Reply: 2


Dreamer Published in 2017-12-06 18:45:53Z

Based on the thread "cmake variable scope, add_subdirectory", the CMake set command will set the variable in the current scope only, unless the PARENT_SCOPE parameter is specified.

Recently when I was looking at the project command, per CMake doc, variables <PROJECT-NAME>_SOURCE_DIR and <PROJECT-NAME>_BINARY_DIR will be set. But it didn't mention what is the scope of these variables. Can these variable be used in other subdirectory? For example:

|- root | |- CMakeLists.txt // add_subdirectory(proj1); add_subdirectory(proj2) | | | |- proj1 | | |- CMakeLists.txt // project(proj1) | | | |- proj2 | | |- CMakeLists.txt // Does this have access to proj1_SOURCE_DIR or // poj1_BINARY_DIR?

What about variables for other command like Find_Package? What is the scope of the <Module>_FOUND variable? Thanks!

compor Reply to 2017-12-10 13:22:43Z

From the documentation of project:

The top-level CMakeLists.txt file for a project must contain a literal, direct call to the project() command; loading one through the include() command is not sufficient. If no such call exists CMake will implicitly add one to the top that enables the default languages (C and CXX).

So, those variables are already there and propagate scopes down the layout.

Now, the project command should normally be used once in project, since it sets up various flags. If your other sub-projects are also required to be built by themselves as standalone, then a common idiom is to have a check like this:

  project(foo CXX)

  # other stuff here

Please note that the PARENT_SCOPE is useful in the context of functions and their call sites.

Dreamer Reply to 2017-12-10 18:21:14Z

I figured out the answer by taking a close look at the cmake source code. The project command is actually setting cache entry at the top level. In this way, $proj1_SOURCE_DIR and $proj1_BINARY_DIR will be available to other sibling scopes.


In sum, for command project(proj1), cmake will do: set(proj1_SOURCE_DIR, CACHE STATIC "") set(proj1_BINARY_DIR, CACHE STATIC "")

Unlike regular set(var value), the cache entry could be shared by other sibling scope.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308963 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO