简体   繁体   中英

CMAKE share variable between subdirectories

I'm trying to access from foo (see below) a variable which is calculated in bar . The approach I observed on SO is to add CACHE INTERNAL to the SET . It works, but I have to invoke the generation of the GNU Make files twice. Looks like the variable is not in cache for the first run so, I get just an empty value.

The structure

CMakeList.txt (top)--
                    |
                    -- CMakeList.txt (foo)
                    |
                    -- CMakeList.txt (bar)

The content Top CMakeList.txt

...
...
ADD_SUBDIRECTORY(foo)
ADD_SUBDIRECTORY(bar)
...
...

Foo CMakeList.txt

...
...
    TARGET_INCLUDE_DIRECTORIES(MyProject SYSTEM PRIVATE
        ${BarPath}
    )
    MESSAGE(STATUS "Bar include path " ${BarPath})
...
...

Bar CMakeList.txt

...
...
SET(BarPath ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL "Path to generated files.")
...
...

Then when I run cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=. -G "CodeBlocks - Unix Makefiles" cmake -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=. -G "CodeBlocks - Unix Makefiles" the MESSAGE from the Foo's file returns empty BarPath . Run it once again and the expected value is populated into variable. Whats wrong?

Foo/CMakeLists.txt is executed by cmake before Bar/CMakeLists.txt .

When you first run cmake :

  1. ${BarPath} is undefined and Foo/CMakeLists.txt prints it as empty.
  2. ${BarPath} is defined and cached by Bar/CMakeLists.txt .

When you run it a second time:

  1. ${BarPath} is found in the cache by Foo/CMakeLists.txt prints it.
  2. ${BarPath} is redefined and cached by Bar/CMakeLists.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM