我有一个 shell 脚本,它接收一个 JSON 文件并输出一个.h
我的目标之一所依赖的文件。看来 CMakeadd_custom_command
是我完成此任务所需的,但我无法生成头文件。我已经尝试了几乎所有我能想到的使用这篇文章和这篇文章中的信息的组合。
下面是我可以创建的最简单的方法来重现我遇到的问题。
我的项目结构如下:
. ├── CMakeLists.txt ├── main.c └── 资源 ├── 生成.sh └── input.json
CMakeLists.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})
主程序
#include <stdio.h>
#include "test_data.h"
int main(int argc, char** argv)
{
printf("%s\n", TEST_DATA);
return 0;
}
资源/生成.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"
}
}