1.CMAKE LEARNING
CMAKE
1
在文件内新建 CMakeLists.txt,main.c
├── CMakeLists.txt
└── main.c
1.1-main.c
#include <stdio.h>
int main()
{
printf("Hello World from t1 Main!\n");
return 0;
}
1.2-CMakeLists.txt
# PROJECT指定工程名称,也可指定编程语言
PROJECT (HELLO)
# 显示定义变量 可以书写多个.c文件
SET(SRC_LIST main.c)
# 向终端输出用户定义信息
MESSAGE(STATUS "This is BINARY dir " ${HELLO_BINARY_DIR})
MESSAGE(STATUS "This is SOURCE dir "${HELLO_SOURCE_DIR})
# 从显示定义变量SRC_LIST 生成名为hello的可执行文件 ${}为变量应用格式
ADD_EXECUTABLE(hello ${SRC_LIST})
1.3 相关操作
mkdir build #在该目录下新建build文件夹,存储cmake文件
构成新的文件目录为
├── build
├── CMakeLists.txt
└── main.c
继续
cd build #进入build文件夹
cmake .. #cmake build上一级文件
此时终端输出以下信息
-- The C compiler identification is GNU 9.4.0
-- The CXX compiler identification is GNU 9.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- This is BINARY dir /home/whf/文档/CMAKE_Text/t1/build
-- This is SOURCE dir /home/whf/文档/CMAKE_Text/t1
-- Configuring done
-- Generating done
-- Build files have been written to: /home/whf/文档/CMAKE_Text/t1/build
上述信息即CMAKE过程,此时文件目录为
├── build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ └── Makefile
├── CMakeLists.txt
└── main.c
在build目录下,终端输入
make #用于生成可执行文件
目录为
├── build
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ ├── hello
│ └── Makefile
├── CMakeLists.txt
└── main.c
这里的hello即为生成的可执行文件,与
# 从显示定义变量SRC_LIST 生成名为hello的可执行文件 ${}为变量应用格式
ADD_EXECUTABLE(hello ${SRC_LIST})
名称一致,修改名称后生成可执行文件名称也随之变化。
执行hello
./hello
输出
Hello World from t1 Main!
即为编译成功。
1.4拓展
这里对main.c做修改,使其可以输入参数,期望完成输入身高、体重并计算BMI输出。
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char* argv[])
{
float weight,high;
printf("共输入%d个参数\n",argc);
if(argc != 4){
printf("请输入4个参数\n");
}
else
{
// 字符串转浮点
high = atof(argv[2]);
weight = atof(argv[3]);
printf("身高为:%fm,体重为:%fkg,BMI为:%f\n",high,weight,weight/high/high);
}
}
重复1.3中cmake、make步骤(可以修改可执行文件名为BMI)
文件目录为
├── build
│ ├── BMI
│ ├── CMakeCache.txt
│ ├── CMakeFiles
│ ├── cmake_install.cmake
│ └── Makefile
├── CMakeLists.txt
└── main.c
执行BMI
whf@whf:~/文档/CMAKE_Text/t1/build$ ./BMI
共输入1个参数
请输入4个参数
只执行BMI相当于输入BMI名称(字符)一个参数,
whf@whf:~/文档/CMAKE_Text/t1/build$ ./BMI 2 1.77 63
共输入4个参数
身高为:1.770000m,体重为:63.000000kg,BMI为:20.109163
这里BMI后的2即为main(int argc,char* argv[]))中的argc,后面两个参数为字符串数组指针内容(地址)
atof()字符串转为浮点型

浙公网安备 33010602011771号