• add_custom_command

MathFunctions 工程的 CMakeLists.txt

# 添加可执行程序 MakeTable
add_executable(MakeTable MakeTable.cxx)
# 添加一个自定义命令,指定如何通过运行 MakeTable 生成 Table.h
add_custom_command(
    OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
    COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
    DEPENDS MakeTable
)
# 将生成的 Table.h 添加到库 MathFunctions 的源代码列表
add_library(MathFunctions 
            mysqrt.cxx
            ${CMAKE_CURRENT_BINARY_DIR}/Table.h
)
# 将当前二进制目录添加到包含目录列表中,这样 Table.h 才能被 mysqrt.cxx 找到并包含
target_include_directories(MathFunctions 
            INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
            PRIVATE ${CMAKE_CURRENT_BINARY_DIR}
)
install(TARGETS MathFunctions DESTINATION lib)
install(FILES MathFunctions.h DESTINATION include)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/Table.h DESTINATION include)

生成的 Table.h 文件

double sqrtTable[] = {
0,
1,
1.41421,
1.73205,
2,
2.23607,
2.44949,
2.64575,
2.82843,
3,
0};

Tutorial.exe 运行结果

.\Release\Tutorial.exe 4.8
Use the table to help find an initial value 
Computing sqrt of 4.8 to be 2.2
Computing sqrt of 4.8 to be 2.19091
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
Computing sqrt of 4.8 to be 2.19089
The square root of 4.8 is 2.19089