// A simple program that builds a sqrt table#include<cmath>#include<fstream>#include<iostream>intmain(int argc,char* argv[]){// make sure we have enough argumentsif(argc <2){return1;}
std::ofstream fout(argv[1], std::ios_base::out);constbool 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}
更改 MathFunctions/CMakeLists.txt 文件
# --add
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
)add_library(MathFunctions
mysqrt.cxx
${CMAKE_CURRENT_BINARY_DIR}/Table.h # Table.h作为目标MathFunctions的源文件
)#statethat anybody linking to us needs to include the current source dir#tofind MathFunctions.h,while we don't.target_include_directories(MathFunctions
INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
PRIVATE ${CMAKE_CURRENT_BINARY_DIR} # 增加Table.h所在路径为目标搜索路径
)#doesthis system provide the log and exp functions?include(CheckSymbolExists)check_symbol_exists(log "math.h" HAVE_LOG)check_symbol_exists(exp "math.h" HAVE_EXP)if(NOT(HAVE_LOG AND HAVE_EXP))unset(HAVE_LOG CACHE)unset(HAVE_EXP CACHE)set(CMAKE_REQUIRED_LIBRARIES "m")check_symbol_exists(log "math.h" HAVE_LOG)check_symbol_exists(exp "math.h" HAVE_EXP)if(HAVE_LOG AND HAVE_EXP)target_link_libraries(MathFunctions PRIVATE m)endif()endif()#addcompile definitionsif(HAVE_LOG AND HAVE_EXP)target_compile_definitions(MathFunctions
PRIVATE "HAVE_LOG""HAVE_EXP")endif()
二 构建
mkdir build
cd build
cmake …
cmake --build .
./Tutorial 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
The square root of 9 is 3