13

How can I call to a cmake file in script mode (-P) from other cmake file, so this "cmake child" knows all variable of its parent? Because, if I have a lot of variables the child needs, I have to write many -D options, and I want to avoid it.

Example:

// CMakeLists.txt
cmake_minimum_required(VERSION 2.8)

set(teststr "Hello World!")

add_custom_command(test
   ${CMAKE_COMMAND} -Dteststr=${teststr} -P test.cmake
)

// test.cmake
message("${teststr}")

$ cmake .
$ make test
Hello world!
Built target test

Works fine!. But, without "-Dteststr":

// CMakeLists.txt
cmake_minimum_required(VERSION 2.8)

set(teststr "Hello World!")

add_custom_command(test
   ${CMAKE_COMMAND} -P test.cmake
)

// test.cmake
message("${teststr}")

$ cmake .
$ make test

Built target test

Of course, without -D option, the "teststr" variable, in test.cmake, is unset, and thus, the output is empty.

Any option to call test.cmake in "heritage mode", or something like that?

2 Answers 2

12

You can pass arguments to a script with cmake -P. If you call:

cmake -P <script-file> <arg3> <arg4> <arg5> ...

then the variables CMAKE_ARGC, CMAKE_ARGV0, CMAKE_ARGV1, ... will be available for the script. See documentation for CMAKE_ARGC and CMAKE_ARGV0.

The other way is to define variables, just like with the non-script cmake command. However there's one thing to be aware of: you need to define the variables before -P:

cmake -DVAR=VALUE -DFOO=BAR -P <script-file> <arg5> <arg6> ...

Now in the cmake VAR and FOO will be available.
Also, note that the numbering of the args after the script-file will be shifted accordingly.

Sign up to request clarification or add additional context in comments.

Comments

5

There's no particularly easy way to do this that I know of.

You could write all the current variables in the parent CMakeLists.txt to a separate file and then include this in your test.cmake:

# CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)
set(teststr "Hello World!")
set(CacheForScript ${CMAKE_BINARY_DIR}/CMakeCacheForScript.cmake)
file(WRITE ${CacheForScript} "")

get_cmake_property(Vars VARIABLES)
foreach(Var ${Vars})
  if(${Var})
    string(REPLACE "\\" "\\\\" ${Var} ${${Var}})
  endif()
  file(APPEND ${CacheForScript} "set(${Var} \"${${Var}}\")\n")
endforeach()

add_custom_target(test ${CMAKE_COMMAND} -P ${CMAKE_SOURCE_DIR}/test.cmake)


# test.cmake
include(${CMAKE_BINARY_DIR}/CMakeCacheForScript.cmake)
message("${teststr}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.