Why variables are not accessed inside script in CM

2019-04-08 11:13发布

I have a script called "install_copy_dlls.cmake", which is called to execute from top level cmake file as shown below.

INSTALL(SCRIPT "install_copy_dlls.cmake")

And, I have a variable named "USE_OSG_STATIC" which is set to ON if I use Statically compiled OpenSceneGraph and set of OFF if I use Dynamically compiled OpenSceneGraph.

I need to use this variable inside install_copy_dlls.cmake script.

so, here is how install_copy_dlls.cmake file should look like.

copy other required dlls...

if(NOT USE_OSG_STATIC) //if dynamic OSG

copy osg dlls

here, I try to use "message" to print USE_OSG_STATIC variable and it doesn't print anything.

Can anyone explain me why I can not use variables in Script file?

标签: cmake
2条回答
走好不送
2楼-- · 2019-04-08 11:41

I found a simpler solution: set the variable in a preceding install() call:

install(CODE "set(A \"${A}\")")
install(SCRIPT cmake/custom_script.cmake)

This ends up rendered into the cmake_install script roughly as:

set(A "Avalue")
include(/path/to/cmake/custom_script.cmake)

which is exactly what you need.

查看更多
不美不萌又怎样
3楼-- · 2019-04-08 11:55
Can anyone explain me why I can not use variables in Script file?

install(SCRIPT ...) command works like cmake -P. So there is no variables forwarded from parent script to child (until you explicitly define one):

> cat run.cmake 
if(A)
  message("A: ${A}")
else()
  message("A is empty")
endif()
> cmake -P run.cmake 
A is empty
> cmake -DA=15 -P run.cmake 
A: 15

Using CMakeLists.txt:

> cat CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
set(A 43)
execute_process(COMMAND ${CMAKE_COMMAND} -P run.cmake)
> cmake -H. -B_builds
A is empty

Forward to child process:

> cat CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
set(A 43)
execute_process(COMMAND ${CMAKE_COMMAND} -DA=${A} -P run.cmake)
> cmake -H. -B_builds 
A: 43

Solution #1 (forwarding)

Using install(CODE ...) command you can define variable for run.cmake script:

> cat CMakeLists.txt
install(
    CODE
    "execute_process(
        COMMAND
        ${CMAKE_COMMAND}
        -DA=${A}
        -P
        ${CMAKE_CURRENT_LIST_DIR}/run.cmake
    )"
)
> cmake -H. -B_builds -DA=554
> cmake --build _builds --target install
Install the project...
-- Install configuration: ""
A: 554

Solution #2 (configuring)

You can configure install script using configure_file command:

> cat run.cmake.in 
set(A @A@)

if(A)
  message("A: ${A}")
else()
  message("A is empty")
endif()
> cat CMakeLists.txt    
set(custom_script ${PROJECT_BINARY_DIR}/custom_install_scripts/run.cmake)
configure_file(run.cmake.in ${custom_script} @ONLY)
install(SCRIPT ${custom_script})
> cmake -H. -B_builds -DA=42
> cmake --build _builds --target install
Install the project...
-- Install configuration: ""
A: 42
查看更多
登录 后发表回答