【发布时间】:2013-02-11 02:17:34
【问题描述】:
我有一个 shell 脚本,它接收一个 JSON 文件并输出一个 .h 文件,这是我的一个目标所依赖的。看起来 CMake 的 add_custom_command 是我需要完成的,但我无法生成头文件。使用this post 和this post 中的信息,我已经尝试了几乎所有我能想到的组合。
下面是我可以创建的最简单的方法来重现我遇到的问题。
我的项目结构如下:
. ├── CMakeLists.txt ├── main.c └── 资源 ├── 生成.sh └── input.jsonCMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(test)
set(TEST_DATA_OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/test_data.h)
add_custom_command(
OUTPUT ${TEST_DATA_OUTPUT}
COMMAND res/generate.sh h res/input.json ${TEST_DATA_OUTPUT}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMENT "Generates the header file containing the JSON data."
)
# add the binary tree to the search path for include files so we
# will fine the generated files
include_directories(${CMAKE_CURRENT_BINARY_DIR})
set(SRCS main.c)
add_executable(test ${SRCS})
main.c
#include <stdio.h>
#include "test_data.h"
int main(int argc, char** argv)
{
printf("%s\n", TEST_DATA);
return 0;
}
res/generate.sh
#!/bin/sh
#
# Converts the JSON to a C header file to be used as a resource file.
print_usage()
{
cat << EOF
USAGE:
$0 h INPUT
DESCRIPTION:
Outputs JSON data to another format.
EOF
}
to_h()
{
cat << EOF
#ifndef TEST_DATA_H
#define TEST_DATA_H
static const char* TEST_DATA =
"$(cat "$1" | sed 's/"/\\"/g' | sed ':a;N;$!ba;s/\n/"\n"/g')";
#endif // TEST_DATA_H
EOF
}
case "$1" in
h)
if [ $# -eq 3 ] ; then
to_h "$2" > "$3"
elif [ $# -eq 2 ] ; then
to_h "$2"
else
echo "no input file specified" 1>&2
fi
;;
*)
print_usage
;;
esac
exit 0
res/input.json
{
"1": {
"attr1": "value1",
"attr2": "value2"
},
"2": {
"attr1": "value1",
"attr2": "value2"
}
}
【问题讨论】:
-
在源代码外构建中,此命令将失败,您的第一个链接提供了解决方案。否则,请阅读和/或提供构建日志以了解构建过程尝试运行您的自定义命令时实际发生的情况。
-
依赖
generated.h的目标是什么?你能告诉我们你的目标吗?add_custom_command只会在您尝试构建它或依赖它的东西时执行。
标签: c cmake build-automation