Cmake 变量作用域,add_subdirectory

在项目根目录中有一个 CMakeLists.txt,在/src 文件夹中有一个。/src 文件夹中的变量只包含一个带有。Cpp 文件(set (SOURCEFILES main.cpp foo.cpp)) ,在根 CMakeLists.txt 中执行 add_subdirectory(src),然后执行 add_executable(MyApp ${SOURCEFILES})

但是 cmake 给了我错误

调用了不正确数量的参数,没有源 提供

如何让 cmake 查看变量?我读到 cmake 只知道全局变量,但显然情况并非如此..。

85737 次浏览

As mentioned in the documentation of the set command, each directory added with add_subdirectory or each function declared with function creates a new scope.

The new child scope inherits all variable definitions from its parent scope. Variable assignments in the new child scope with the set command will only be visible in the child scope unless the PARENT_SCOPE option is used.

To make the SOURCEFILES assignment visible in the root folder of your project, try:

set (SOURCEFILES main.cpp foo.cpp PARENT_SCOPE)