cmake add_custom_command

19

我正在为add_custom_command而苦苦挣扎。让我详细解释一下问题。

我有一组cxx文件和hxx文件。我对每个文件都运行一个perl脚本,以生成某种类型的翻译文件。命令看起来像这样

perl trans.pl source.cxx -o source_cxx_tro

对于header.hxx文件也是如此。

因此,我最终会得到一些多个命令(每个命令对应一个文件)。

然后我对这些命令生成的输出(source_cxx_tro、header_hxx_tro)再运行另一个Perl脚本。

perl combine.pl source_cxx_tro header_hxx_tro -o dir.trx

dir.trx是输出文件。

我有类似这样的东西。

Loop_Over_All_Files()
Add_Custom_Command (OUTPUT ${trofile} COMMAND perl trans.pl ${file} -o ${file_tro})
List (APPEND trofiles ${file_tro})
End_Loop()

Add_Custom_Command (TARGET LibraryTarget POST_BUILD COMMAND perl combine.pl ${trofiles} -o LibraryTarget.trx)

我期望的是在构建 post build 目标时,先构建 trofiles。但事实并非如此。${trofiles} 没有被构建,因此 post build 命令以失败结束。 有没有办法让 POST_BUILD 命令依赖于前一个自定义命令?

有什么建议吗?

谢谢, Surya

2个回答

32
使用add_custom_command创建文件转换链:
*.(cxx|hxx) -> *_(cxx|hxx)_tro *_(cxx|hxx)_tro -> Foo.trx
然后使用add_custom_target将最后一个转换作为cmake的一级实体。默认情况下,此目标不会被构建,除非您使用ALL标记它或让其他构建的目标依赖于它。
代码示例:
```cmake set(SOURCES foo.cxx foo.hxx) add_library(Foo ${SOURCES})
set(trofiles) foreach(_file ${SOURCES}) string(REPLACE "." "_" file_tro ${_file}) set(file_tro "${file_tro}_tro") add_custom_command( OUTPUT ${file_tro} COMMAND perl ${CMAKE_CURRENT_SOURCE_DIR}/trans.pl ${CMAKE_CURRENT_SOURCE_DIR}/${_file} -o ${file_tro} DEPENDS ${_file} ) list(APPEND trofiles ${file_tro}) endforeach() add_custom_command( OUTPUT Foo.trx COMMAND perl ${CMAKE_CURRENT_SOURCE_DIR}/combine.pl ${trofiles} -o Foo.trx DEPENDS ${trofiles} ) add_custom_target(do_trofiles DEPENDS Foo.trx) add_dependencies(Foo do_trofiles) ```

3
您想创建一个自定义目标,以消耗自定义命令的输出。然后使用ADD_DEPENDENCIES确保命令按正确顺序运行。
以下是可能接近您想要的内容: https://gitlab.kitware.com/cmake/community/-/wikis/FAQ#how-do-i-use-cmake-to-build-latex-documents 基本上,为每个生成的文件添加一个add_custom_command,收集这些文件的列表(trofiles),然后在列表trofiles上使用add_custom_target,并使用DEPENDS进行设置。 然后使用add_dependencies使LibraryTarget依赖于自定义目标。 然后在构建库目标之前应先构建自定义目标。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接