简体   繁体   English

CMake在构建之前运行自定义命令?

[英]CMake run custom command before build?

Example source of a binary I want to run before each build, once per add_executable : 我想在每个构建之前运行一个二进制示例源,每个add_executable一次:

#include <stdio.h>

int main(int argc, char *argv[]) {
    for(int i=0; i<argc; ++i)
        printf("argv[%d] = %s\n", i, argv[i]);
    fclose(fopen("foo.hh", "a"));
}

CMakeLists.txt CMakeLists.txt

cmake_minimum_required(VERSION 3.5)
project(foo_proj)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
set(SOURCE_FILES main.cpp)
# ---- this line changes ----
add_executable(foo_proj ${SOURCE_FILES})

Attempts: 尝试次数:

add_custom_target(create_foo_hh COMMAND /tmp/bin/create_foo_hh)
add_dependencies(${SOURCE_FILES} create_foo_hh)

Error:Cannot add target-level dependencies to non-existent target "main.cpp". 错误:无法将目标级别的依赖项添加到不存在的目标“ main.cpp”。 The add_dependencies works for top-level logical targets created by the add_executable, add_library, or add_custom_target commands. 该add_dependencies工程由add_executable,add_library,或add_custom_target命令创建顶级逻辑的目标。 If you want to add file-level dependencies see the DEPENDS option of the add_custom_target and add_custom_command commands. 如果您要添加的文件级依赖看到add_custom_target和add_custom_command命令的depends参数。

execute_process(COMMAND /tmp/bin/create_foo_hh main.cpp)

No error, but foo.hh isn't created. 未创建没有错误,但foo.hh。

How do I automate the running of this command? 如何自动运行此命令?

execute_process() is invoked at configuration time. 在配置时调用execute_process()

You can use add_custom_command() : 您可以使用add_custom_command()

add_custom_command(
  OUTPUT foo.hh
  COMMAND /tmp/bin/create_foo_h main.cpp
  DEPENDS ${SOURCE_FILES} /tmp/bin/create_foo_hh main.cpp
  WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
)
include_directories(${CMAKE_CURRENT_BINARY_DIR})
add_executable(foo_proj ${SOURCE_FILES} foo.hh)

That way, foo.hh is a dependency of foo_proj : and your command will be invoked when building foo_proj . 这样, foo.hhfoo.hh的依赖foo_proj :并且在构建foo_proj时将调用您的命令。 It depends on ${SOURCE_FILES} and /tmp/bin/create_foo_hh main.cpp so that it is generated again if one of those files changes. 它取决于${SOURCE_FILES}/tmp/bin/create_foo_hh main.cpp以便在其中一个文件更改时再次生成该文件。

Regarding paths, add_custom_command() is configured to run in the current build directory to generate the file there, and include_directories() is used to add the build directory to the include dirs. 关于路径,将add_custom_command()配置为在当前构建目录中运行以在其中生成文件,并使用include_directories()将构建目录添加至包含目录。

您可能不希望自定义目标依赖于您的源文件(因为它们不是目标文件本身,因此从不“运行”),而是取决于您使用它们创建的目标文件:

target_add_dependencies(foo_proj create_foo_hh)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM