为什么 CMake 看不到 FLEX 生成的源文件?

Why CMake does not see FLEX generated source files?

我正在尝试使用 CMake 设置 flex,但是,在构建项目时出现以下错误:

[proc] Executing command: /usr/bin/cmake --build /mnt/d/Files/C/parser/build --config Debug --target all -- -j 14
[build] [ 33%] [FLEX][parser] Building scanner with flex 2.6.4
[build] Scanning dependencies of target parser
[build] make[2]: Warning: File 'CMakeFiles/parser.dir/depend.make' has modification time 0.15 s in the future
[build] [ 33%] [FLEX][parser] Building scanner with flex 2.6.4
[build] [ 66%] Building C object CMakeFiles/parser.dir/lex.yy.c.o
[build] gcc: error: /mnt/d/Files/C/parser/build/lex.yy.c: No such file or directory
[build] gcc: fatal error: no input files
[build] compilation terminated.
[build] make[2]: *** [CMakeFiles/parser.dir/build.make:67: CMakeFiles/parser.dir/lex.yy.c.o] Error 1
[build] make[1]: *** [CMakeFiles/Makefile2:131: CMakeFiles/parser.dir/all] Error 2
[build] make: *** [Makefile:117: all] Error 2
[build] Build finished with exit code 2

我的CMakeLists.txt如下:

cmake_minimum_required(VERSION 3.0.0)
project(parser C)

find_package(FLEX REQUIRED)

include(CTest)
enable_testing()

set(SOURCE_PATH source)
flex_target(parser ${SOURCE_PATH}/parser.l lex.yy.c)

add_executable(parser ${FLEX_parser_OUTPUTS})

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

所有源文件(目前为 parser.l 文件)都位于 /source 文件夹中,相对于项目文件夹。

我做错了什么?这是我第一次尝试使用 CMake 设置 FLEX,所以我对这里出了什么问题有点困惑。

您应该在 flex_target 命令中指定输出文件的 完整 路径(如 documentation 中的示例所示):

flex_target(parser ${SOURCE_PATH}/parser.l ${CMAKE_CURRENT_BINARY_DIR}/lex.yy.c)

因为这是一个生成的文件,你应该把它放在CMake二进制目录中。