0x00 前言
文章中的文字可能存在语法错误以及标点错误,请谅解;
如果在文章中发现代码错误或其它问题请告知,感谢!
cmake version: 3.10.2
系统版本:Ubuntu 18.04.4 LTS \n \l
最后更新:2021-12-02
0x01 option()指令说明
cmake
中的option()
函数起到编译开关的作用,语法如下:
option(<variable> "<help_text>" [value])
variable
是变量名。help_text
是描述信息。value
是变量初始值,只能是ON
或OFF
。
主义CMakeLists.txt中位于option()之前的语句,变量按未定义处理,option()函数之后的语句,变量才被定义。
1.程序实例
程序实例源代码github地址:
https://github.com/fyw4/CSDN-Blog-Code/tree/master/CMake/cmake_option
文件目录结构如下:
CMakeLists.txt
文件内容:
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
PROJECT(TEST)
if(TEST)
message("TEST is defined,vlaue:${TEST}")
else()
message("TEST is not defined")
endif()
option(TEST "test affect to code" ON)
ADD_EXECUTABLE(TEST main.cpp)
if(TEST)
message("TEST is defined,vlaue:${TEST}")
else()
message("TEST is not defined")
endif()
main.cpp
内容:
#include<iostream>
using namespace std;
int main()
{
#ifdef TEST
cout << "hello TEST" << endl;
#else
cout << "hello world" << endl;
#endif
return 0;
}
依次执行:
#cmake .
#make
#./TEST
运行结果:
可以看到,main
程序在执行时没有识别TEST
,说明option
指令对变量的定义不影响源码中的#ifdef
或者#ifndef
逻辑判断。
如果想要CMakeLists.txt
中的变量定义对源码生效,可以在CMakeLists.txt
中使用add_definitions()
函数指令。
0x02 add_definitions()指令说明
add_definitions()
语法如下:
add_definitions(-DFOO -DBAR ...)
参数为向 C/C++编译器添加-D 定义
2.程序实例
程序实例源代码github地址:
https://github.com/fyw4/CSDN-Blog-Code/tree/master/CMake/cmake_add_definitions
文件目录结构如下:
CMakeLists.txt
文件内容:
CMAKE_MINIMUM_REQUIRED(VERSION 3.5)
PROJECT(TEST)
option(TEST "test affect to code" OFF)
if(TEST)
message("TEST is defined,vlaue:${TEST}")
add_definitions(-DTEST_DEBUG)
else()
message("TEST is not defined")
endif()
ADD_EXECUTABLE(TEST main.cpp)
main.cpp
内容:
#include<iostream>
using namespace std;
int main()
{
#ifdef TEST_DEBUG
cout << "hello TEST" << endl;
#else
cout << "hello world" << endl;
#endif
return 0;
}
依次执行:
#cmake -DTEST=1 .
#make
#./TEST
运行结果:
最后输出是"hello TEST"
,如果我们不对#cmake
加任何参数执行如下:
#cmake .
#make
#./TEST
可以看到运行结果为输出“hello world”
:
以上。
参考文档:
1.https://blog.csdn.net/weixin_42108533/article/details/119119445
2.https://blog.csdn.net/fb_941219/article/details/107376017?spm=1001.2101.3001.6661.1&utm_medium=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link