How to load variables in a “bar=foo” syntax in CMake?

 ̄綄美尐妖づ 提交于 2019-12-07 05:21:36

问题


It is nice to be able to share the same file between a Makefile and shell scripts due to the fact that they both can cope with the following syntax for key-value pairs:

$> cat config 
  var1=value
  var2=value
  var3=value
  var4=value
  var5=value

So, just a source config from a shell script will be fine, as well as include config from a Makefile. However, with CMake the syntax becomes SET(var1 value). Is there some easy way that I can feed CMake with a file with variables using the syntax of above? I mean easy in the sense that I do not like to run e.g. sed over it.


回答1:


@Guillaume's answer is ideal for generating a config file from within your CMakeLists.txt.

However, if you're looking to import the contents of a config file like this into your CMake environment, you'll need to add something like:

file(STRINGS <path to config file> ConfigContents)
foreach(NameAndValue ${ConfigContents})
  # Strip leading spaces
  string(REGEX REPLACE "^[ ]+" "" NameAndValue ${NameAndValue})
  # Find variable name
  string(REGEX MATCH "^[^=]+" Name ${NameAndValue})
  # Find the value
  string(REPLACE "${Name}=" "" Value ${NameAndValue})
  # Set the variable
  set(${Name} "${Value}")
endforeach()



回答2:


Create a config.in file with all variables you want to "extract" of your CMakeLists:

var1=@VAR1@
var2=@VAR2@
var3=@VAR3@
var4=@VAR4@
var5=@VAR4@

and add a configure_file call in your CMakeLists.txt:

configure_file(
    ${CMAKE_CURRENT_SOURCE_DIR}/config.in
    ${CMAKE_CURRENT_BINARY_DIR}/config
    @ONLY
)

This will create a config file.



来源:https://stackoverflow.com/questions/17165905/how-to-load-variables-in-a-bar-foo-syntax-in-cmake

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!