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.
@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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With