
CMake教程06-添加自定义命令和生成的文件
添加自定义命令和生成的文件
如果我们不想使用系统的
log
和exp
计算平方根,而使用自定义的计算方法,我们要怎么做呢?
本节,我们就来做这件事。
本节添加自定义命令MakeTable
用于生成平方根初始化表,并且使用MakeTable
生成的Table.h
头文件中定义的初始化表sqrtTable
,接下来我们来看下具体操作。
首先,取消func/CMakeLists.txt
中关于log
和exp
函数的设置,在删除myfunc.cpp
中HAVE_LOG
宏内部代码及头文件#include<cmath>
。
在./func
目录下添加一个新文件MakeTable.cxx
,内容如下:
// File:MakeTable.cxx A simple program that builds a sqrt table
#include <cmath>
#include <fstream>
#include <iostream>
int main(int argc, char* argv[])
{
// make sure we have enough arguments
if (argc < 2) {
return 1;
}
std::ofstream fout(argv[1], std::ios_base::out);
const bool fileOpen = fout.is_open();
if (fileOpen) {
fout << "double sqrtTable[] = {" << std::endl;
for (int i = 0; i < 10; ++i) {
fout << sqrt(static_cast<double>(i)) << "," << std::endl;
}
// close the table with a zero
fout << "0};" << std::endl;
fout.close();
}
return fileOpen ? 0 : 1; // return 0 if wrote the file
}
接下来,我们就可以构建自定义命令。
首先,修改./func/CMakeLists.txt
文件,添加生成可执行程序语句:
add_executable(MakeTable MakeTable.cxx)
然后,添加一个自定义命令,执行并生成Table.h
文件:
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
DEPENDS MakeTable
)
接下来,让CMake
知道myfunc.cpp
依赖刚生成的Table.h
:
add_library(myfunc
myfunc.cpp
${CMAKE_CURRENT_BINARY_DIR}/Table.h
)
当然,我们为了让myfunc.cpp
能找到Table.h
,还需要使用target_include_directories
添加其所在目录:
target_include_directories(myfunc
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
PRIVATE ${CMAKE_CURRENT_BINARY_DIR}
)
到这里,我们就可以重新构建项目了,构建成功后,执行可执行程序./first_app
验证下是否已经使用了sqrtTable
。
$ ./first_app 9
Use the table to help find an initial value
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
Computing sqrt of 9 to be 3
$ ./first_app 10
Computing sqrt of 10 to be 5.5
Computing sqrt of 10 to be 3.65909
Computing sqrt of 10 to be 3.19601
Computing sqrt of 10 to be 3.16246
Computing sqrt of 10 to be 3.16228
Computing sqrt of 10 to be 3.16228
Computing sqrt of 10 to be 3.16228
Computing sqrt of 10 to be 3.16228
Computing sqrt of 10 to be 3.16228
Computing sqrt of 10 to be 3.16228
到此本节内容就结束了,本节介绍了如何添加自定义命令MakeTable
,以及如何使用动态生成的Table.h
文件的方法,你可以实践练习一下,这样可以让你快速理解本节内容。
转载本文时请注明出处及本文链接地址CMake教程06-添加自定义命令和生成的文件。