使用 cmake 3.12 可以尝试这样的事情:
file(STRINGS config CONFIG REGEX "^[ ]*[A-Za-z0-9_]+[ ]*=")
list(TRANSFORM CONFIG STRIP)
list(TRANSFORM CONFIG REPLACE "([^=]+)=[ ]*(.*)" "set(\\1 \"\\2\")\n")
cmake_language(EVAL CODE ${CONFIG})
# just for test
message(STATUS "a=\"${a}\"")
message(STATUS "b=\"${b}\"")
测试:
rion@dizzynb ~/temp $ cmake --trace -P test.cmake
Running with trace output on.
/home/rion/temp/test.cmake(1): file(STRINGS config CONFIG REGEX ^[ ]*[A-Za-z0-9_]+[ ]*= )
/home/rion/temp/test.cmake(2): list(TRANSFORM CONFIG STRIP )
/home/rion/temp/test.cmake(3): list(TRANSFORM CONFIG REPLACE ([^=]+)=[ ]*(.*) set(\\1 \"\\2\")\n )
/home/rion/temp/test.cmake(4): cmake_language(EVAL CODE ${CONFIG} )
/home/rion/temp/test.cmake:4:EVAL(1): set(a hello world )
/home/rion/temp/test.cmake:4:EVAL(2): set(b 10 )
/home/rion/temp/test.cmake(6): message(STATUS a=\"${a}\" )
-- a="hello world"
/home/rion/temp/test.cmake(7): message(STATUS b=\"${b}\" )
-- b="10"
rion@dizzynb ~/temp $ cat config
# this is my config
a=hello world
b = 10
#c= O_o
但请记住,上面的 eval 对于某些内容可能不可靠。