Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 426
Anne van Rossum Avatar asked Jun 18 '13 09:06

Anne van Rossum


2 Answers

@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()
like image 132
Fraser Avatar answered Sep 18 '22 13:09

Fraser


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.

like image 38
Guillaume Avatar answered Sep 17 '22 13:09

Guillaume