cmake--代码生成
前言
cmake能够支持生成代码, 常用于生成版本信息以及文件路径等。
一, 目录结构
├── CMakeLists.txt
├── main.cpp
├── path.h.in
├── ver.h.in
* link:CMakeLists.txt[] - Contains the CMake commands you wish to run
* link:main.cpp[] - The source file with main
--------------------------------------
#include <iostream>
#include "ver.h"
#include "path.h"
int main(int argc, char *argv[])
{
std::cout << "Hello Version " << ver << "!" << std::endl;
std::cout << "Path is " << path << std::endl;
return 0;
}
------------------------------------------------
* link:path.h.in[] - File to contain a path to the build directory
------------------------------------------------
#ifndef __PATH_H__
#define __PATH_H__
// version variable that will be substituted by cmake
// This shows an example using the @ variable type
const char* path = "@CMAKE_SOURCE_DIR@";
#endif
------------------------------------------------
* link:ver.h.in[] - File to contain the version of the project
------------------------------------------------
#ifndef __VER_H__
#define __VER_H__
// version variable that will be substituted by cmake
// This shows an example using the $ variable type
const char* ver = "${cf_example_VERSION}";
#endif
------------------------------------------------
二,cmake脚本
cmake_minimum_required(VERSION 3.5)
project (cf_example)
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}")
# 将ver.h.in文件替换为ver.h文件移动到编译目录中,并将ver.h.in的cmake变量替换为字符串
configure_file(ver.h.in ${PROJECT_BINARY_DIR}/ver.h)
# 将path.h.in文件替换为path.h文件移动到编译目录,并将path.h的cmake变量替换为路径字符串
configure_file(path.h.in ${PROJECT_BINARY_DIR}/path.h @ONLY)
add_executable(cf_example
main.cpp
)
# 将生成的头文件添加到包含的目录,CMAKE_BINARY_DIR为编译目录。
target_include_directories( cf_example
PUBLIC
${CMAKE_BINARY_DIR}
)
三,扩展分析
可以使用"${cf_example_VERSION}"和"@CMAKE_SOURCE_DIR@"两种方式设置配置文件的cmake变量。