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

@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.