简体   繁体   English

使用CMake add_custom_command为另一个目标生成源

[英]Use CMake add_custom_command to generate source for another target

I tried this dummy example: 我尝试了这个虚拟的例子:

CMakeLists.txt 的CMakeLists.txt

cmake_minimum_required( VERSION 2.8 )
project( testcmake )

add_custom_command(
  OUTPUT testcmake.h
  COMMAND xxd -i testcmake.txt testcmake.h
  DEPENDS testcmake.txt
)

add_executable( testcmake testcmake.c testcmake.h )

testcmake.c testcmake.c

#include <stdio.h>
#include "testcmake.h"

int main()
{
    int i;

    for ( i = 0 ; i < testcmake_txt_len ; i++ )
    {
        fputc( testcmake_txt[ i ] , stdout );
    }
}

testcmake.txt testcmake.txt

foo
bar
baz

The problem 问题

It fails with: 它失败了:

[...]
xxd: testcmake.txt: No such file or directory
[...]

Adding WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} makes everything works fine but I don't want the output of my custom command appears in my source directory, I want that all the intermediate files remain in the CMake build directory just like any non custom rule. 添加WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}使一切正常但我不希望我的自定义命令的输出出现在我的源目录中,我希望所有中间文件都保留在CMake构建目录中,就像任何非自定义规则一样。

You need to copy testcmake.txt to your build folder before executing xxd. 在执行xxd之前,需要将testcmake.txt复制到build文件夹。 You'll also need to add your build directory to the includes so that #include "testcmake.h" works: 您还需要将您的构建目录添加到包含,以便#include "testcmake.h"工作:

add_custom_command(
  OUTPUT testcmake.h
  COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/testcmake.txt testcmake.txt
  COMMAND xxd -i testcmake.txt testcmake.h
  DEPENDS testcmake.txt
)

include_directories(${CMAKE_CURRENT_BINARY_DIR})

With CMake 3.2, file gained a new feature. 使用CMake 3.2, file获得了一项新功能。 Quoting from the release announcement: 引用发布公告:

the "file(GENERATE)" command can now generate files that are used as source files for build system targets. “file(GENERATE)”命令现在可以生成用作构建系统目标的源文件的文件。

Maybe this is easier to use, given you can switch to CMake 3.2. 也许这更容易使用,因为你可以切换到CMake 3.2。

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

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