2. add_subdirectory (MathFunctions)
3. #
引
⼊
可
执
⾏
⽂
件
4. add_executable (Tutorial tutorial.cxx)
5. target_link_libraries (Tutorial MathFunctions)
现
在
,
让
我
们
考
虑
下
让
MathFunctions
库
变
为
可
选
的
。
在
本
指
南
中
,
确
实
没
有
必
要
这
样
画
蛇
添
⾜
;
但
是
对
于
更
⼤
型
的
库
或
者
依
赖
于
第
三
⽅
代
码的
库
,
你
可
能
需
要
这
种
可
选
择
性
。
第
⼀
步
是
为
顶
层
的
CMakeLists
⽂
件
添
加
⼀个
选
项
:
1. #
我
们
应
该
使
⽤
我
们
⾃
⼰
的
数
学
函
数
吗
?
2. option (USE_MYMATH "Use tutorial provided math implementation" ON)
这
将
会
在
CMake
的
GUI
中
显
示
⼀个
默
认
的
ON
值
,
并
且
⽤
户
可
以
随需
改
变
这
个
设
置
。
这
个
设
置
会
被
存
储
在
cache
中
,
那
么
⽤
户
将
不
需
要
在
cmake
该
⼯
程
时
,
每次
都
设
置
这
个
选
项
。
第
⼆
处
改
变
是
,
让
链
接
MathFunctions
库
变
为
可
选
的
。
要
实
现
这
⼀
点
,
我
们修
改
顶
层
CMakeLists
⽂
件
的
结
尾
部
分
:
1. #
添
加
MathFunctions
库
吗
?
2. if (USE_MYMATH)
3. include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
4. add_subdirectory (MathFunctions)
5. set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
6. endif (USE_MYMATH)
7. #
添
加
可
执
⾏
⽂
件
8. add_executable (Tutorial tutorial.cxx)
9. target_link_libraries (Tutorial ${EXTRA_LIBS})
这
⾥
⽤
USE_MYMATH
设
置
来
决
定
是
否
MathFunctions
应
该被
编
译
和
执
⾏
。
注
意
到
,
要
⽤
⼀个
变
量
(
在
这
⾥
是
EXTRA_LIBS
)
来
收
集
所
有
以
后
会
被
连
接
到
可
执
⾏
⽂
件中
的
可
选
的
库
。
这
是
保
持
带
有
许
多
可
选部
件
的
较
⼤
型
⼯
程
⼲
净
清
爽
的
⼀
种
通
⽤
的
⽅
法
。
源
代
码
对
应
的
改
变
相
当
直⽩
,
如
下
所
示
:
1. //
计
算
⼀个
数
平
⽅
根
的
简
单
程
序
2. #include <stdio.h>
3. #include <stdlib.h>
4. #include <math.h>
5. #include "TutorialConfig.h"
6. #ifdef USE_MYMATH
7. #include "MathFunctions.h"
8. #endif
9.
10. int main (int argc, char *argv[]) {
11. if (argc < 2) {
12. fprintf(stdout,"%s Version %d.%d\n", argv[0],
13. Tutorial_VERSION_MAJOR,
14. Tutorial_VERSION_MINOR);
15. fprintf(stdout,"Usage: %s number\n",argv[0]);
16. return 1;
17. }
18.
19. double inputValue = atof(argv[1]);
20.
21. #ifdef USE_MYMATH
22. double outputValue = mysqrt(inputValue);
23. #else
24. double outputValue = sqrt(inputValue);
25. #endif
26.
27. fprintf(stdout,"The square root of %g is %g\n", inputValue, outputValue);
28. return 0;
29. }
评论1
最新资源