gpt4 book ai didi

cmake - 将 compile_commands.json 复制到项目根文件夹

转载 作者:行者123 更新时间:2023-12-03 22:05:38 31 4
gpt4 key购买 nike

我有一个 CMakeLists.txt在我的项目的根目录中 CMAKE_EXPORT_COMPILE_COMMANDS打开。

我正在文件夹中构建目标并通过 add_subdirectory 调用.该文件夹有自己的 CMakeLists.txt文件。
compile_commands.json建在二进制目录的根目录下,我想在运行cmake命令后将其复制到源目录的根目录。

我尝试了两种方法。

  • add_custom_targetadd_custom_command .
    我创建了一个虚拟目标。我将此目标用于 add_custom_command复制文件,但它不会触发 add_custom_command 中的命令.
  • file(COPY ...)第一次触发命令时,compile_commands.json不是通过 cmake 创建的。我不想运行两次 cmake 命令来获取副本 compile_commands.json到源文件夹的根目录。
  • CMAKE_MINIMUM_REQUIRED(VERSION 3.8)
    project(exec LANGUAGES CXX)
    set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

    add_subdirectory("DirectoyWithTarget")

    add_custom_target(copy_compile_commands
    DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json)
    add_custom_command(
    TARGET copy_compile_commands
    PRE_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
    ${CMAKE_CURRENT_BINARY_DIR}/compile_commands.json
    ${CMAKE_CURRENT_SOURCE_DIR}/compile_commands.json
    )
    compile_commands.json文件未复制到 ${CMAKE_CURRENT_SOURCE_DIR} .这意味着 add_custom_command未触发。

    最佳答案

    还没有测试这么多,但这里有两个我想出的基于 cmake 的解决方案。

    选项1

    更少的代码,但总是运行。

    add_custom_target(
    copy-compile-commands ALL
    ${CMAKE_COMMAND} -E copy_if_different
    ${CMAKE_BINARY_DIR}/compile_commands.json
    ${CMAKE_CURRENT_LIST_DIR}
    )

    选项 2

    更多代码,但会设置依赖项,因此除非需要,否则不会运行。可以处理在二进制目录中删除 compile_commands.json 的情况。
    # Copy to source directory
    add_custom_target(
    copy-compile-commands ALL
    DEPENDS
    ${CMAKE_CURRENT_LIST_DIR}/compile_commands.json
    )
    add_custom_command(
    OUTPUT ${CMAKE_CURRENT_LIST_DIR}/compile_commands.json
    COMMAND ${CMAKE_COMMAND} -E copy_if_different
    ${CMAKE_BINARY_DIR}/compile_commands.json
    ${CMAKE_CURRENT_LIST_DIR}/compile_commands.json
    DEPENDS
    # Unlike "proper" targets like executables and libraries,
    # custom command / target pairs will not set up source
    # file dependencies, so we need to list file explicitly here
    generate-compile-commands
    ${CMAKE_BINARY_DIR}/compile_commands.json
    )

    # Generate the compilation commands. Necessary so cmake knows where it came
    # from and if for some reason you delete it.
    add_custom_target(generate-compile-commands
    DEPENDS
    ${CMAKE_BINARY_DIR}/compile_commands.json
    )
    add_custom_command(
    OUTPUT ${CMAKE_BINARY_DIR}/compile_commands.json
    COMMAND ${CMAKE_COMMAND} -B${CMAKE_BINARY_DIR} -S${CMAKE_SOURCE_DIR}
    )

    关于cmake - 将 compile_commands.json 复制到项目根文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464766/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com