Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share variables between different CMake files

Tags:

How do I share variables between different CMake files, and I show the following examples to illustrate my question:

Main

cmake_minimum_required(VERSION 2.6) project(test) set(Var3 "Global variable")  add_subdirectory(${test_SOURCE_DIR}/exe) add_subdirectory(${test_SOURCE_DIR}/dll) 

EXE file

set(Var1 "this is variable 1") set(Var1 ${Var1} " added to varible 1") message(STATUS ${Var1}) 

DLL file

set(Var2 "this is variable 2") message(STATUS ${Var2}) message(STATUS ${Var1}) message(STATUS ${Var3}) 

In this example, Var3 can be seen in the CMake files of exe and dll as it is defined in Main. However, Var1, which is defined in exe, will not be observed in dll. I was just curious: is there a way to make Var1 defined in exe observable in dll?

like image 249
feelfree Avatar asked Nov 08 '13 11:11

feelfree


People also ask

How do you pass a variable in CMake?

Options and variables are defined on the CMake command line like this: $ cmake -DVARIABLE=value path/to/source You can set a variable after the initial `CMake` invocation to change its value. You can also undefine a variable: $ cmake -UVARIABLE path/to/source Variables are stored in the `CMake` cache.

What does add_subdirectory do in CMake?

Add a subdirectory to the build. Adds a subdirectory to the build. The source_dir specifies the directory in which the source CMakeLists.

Where are CMake variables stored?

Cache variables are stored in the CMake cache file, and are persisted across CMake runs.

What is CMakeCache txt?

The CMake cache may be thought of as a configuration file. The first time CMake is run on a project, it produces a CMakeCache. txt file in the top directory of the build tree. CMake uses this file to store a set of global cache variables, whose values persist across multiple runs within a project build tree.


2 Answers

Beside what Tadeusz correctly said, you can make a variable visible at any level (not just one up!) by using

set(Var1 "This is variable 1" CACHE INTERNAL "") 

The variable will be available for all the CMake instructions that follow that instruction, so for example it won't be available for a sister directory that is added before the directory where this variable is defined.

like image 79
Antonio Avatar answered Sep 30 '22 02:09

Antonio


The scopes of variable visibility form a tree. The CMakeFiles.txt files added with add_subdirectory have access to the variables defined in themselves, and in the parent scope (the toplevel global scope in your example).

You can export a variable one level up using:

set(Var1 "This is variable 1" PARENT_SCOPE) 
like image 24
Tadeusz A. Kadłubowski Avatar answered Sep 30 '22 03:09

Tadeusz A. Kadłubowski