代码生成是指使用一些通用的描述文件,可以自动生成源代码,这样可以更高效。
$ tree
.
├── CMakeLists.txt
├── main.cpp -- 源文件
├── path.h.in -- 包含 build 文件目录信息的文件
├── ver.h.in -- 包含项目版本号的文件
在一个文件中需要做变量替换可以使用 configure_file()命令。这个命令的输入和输出主要就是需要修改的源文件和目标文件。
configure_file(ver.h.in ${PROJECT_BINARY_DIR}/ver.h)
configure_file(path.h.in ${PROJECT_BINARY_DIR}/path.h @ONLY)
上面的命令会替换 xxx.h.in 中:${} 语法或者是 @@ 语法的内容,然后会在上面指定的路径下产生一个新的文件。例如:
const char* ver = "${cf_example_VERSION}";const char* path = "@CMAKE_SOURCE_DIR@"
CMakeLists.txt 中需要添加相关内容:
project (cf_example)# set a project version
set (cf_example_VERSION_MAJOR 0)
set (cf_example_VERSION_MINOR 2)
set (cf_example_VERSION_PATCH 1)
set (cf_example_VERSION "${cf_example_VERSION_MAJOR}.${cf_example_VERSION_MINOR}.${cf_example_VERSION_PATCH}")
protobuf 是谷歌的一个工具,用户提供 .proto 文件,里面包含对数据结构的描述, Protobuf ccompiler 就会自动将这些文件描述转成 C++ 源码。
这里需要依赖Protobuf, 所以环境中需要先安装:
sudo apt-get install protobuf-compiler libprotobuf-dev
有一些变量可以供我们使用:
更多地变量内容可以在环境中的 FindProtobuf.make 文件中查看。
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS AddressBook.proto)
上面命令之后就可以使用相关路径来构建我们的项目了:
add_executable(pb_bin main.cpp ${PROTO_SRCS} ${PROTO_HDRS })
完整 CMakeLists.txt:
cmake_minimum_required(VERSION 3.5)# Set the project name
project (protobuf_example)# find the protobuf compiler and libraries
find_package(Protobuf REQUIRED)# check if protobuf was found
if(PROTOBUF_FOUND)message ("protobuf found")
else()message (FATAL_ERROR "Cannot find Protobuf")
endif()# Generate the .h and .cxx files
PROTOBUF_GENERATE_CPP(PROTO_SRCS PROTO_HDRS AddressBook.proto)# Print path to generated files
message ("PROTO_SRCS = ${PROTO_SRCS}")
message ("PROTO_HDRS = ${PROTO_HDRS}")# Add an executable
add_executable(protobuf_examplemain.cpp${PROTO_SRCS}${PROTO_HDRS})target_include_directories(protobuf_examplePUBLIC${PROTOBUF_INCLUDE_DIRS}${CMAKE_CURRENT_BINARY_DIR}
)# link the exe against the libraries
target_link_libraries(protobuf_examplePUBLIC${PROTOBUF_LIBRARIES}
)
在 CMake 中还支持借助其他工具来做代码检查,包括代码风格等。还有单元测试,打包等高阶内容。余下的内容暂时还不需要深入了解,所以这里暂时不继续学习下去了,后续有需要再打开学习。感兴趣的同学可以移步到原项目进行观看。