Cmake与Makefile
也许你会想到makefile,makefile不就是管理代码自动化编译的工具吗?为什么还要用别的构建工具?
其实,cmake和autotools正是makefile的上层工具,它们的目的正是为了产生可移植的makefile,并简化自己动手写makefile时的巨大工作量。如果你自己动手写过makefile,你会发现,makefile通常依赖于你当前的编译平台,而且编写makefile的工作量比较大,解决依赖关系时也容易出错。因此,对于大多数项目,应当考虑使用更自动化一些的 cmake或者autotools来生成makefile,而不是上来就动手编写。
总之,项目构建工具能够帮我们在不同平台上更好地组织和管理我们的代码及其编译过程,这是我们使用它的主要原因。
一、什么是cmake?
cmake的定义是什么 ?——-⾼级编译配置⼯具
cmake就是将多个cpp、hpp文件组合构建为一个大工程的语言。他能够输出各种各样的makefile或者project文件,所有操作都是通过编译CMakeLists.txt来完成。
二、cmake快速使用例子
1.步骤⼀,写⼀个HelloWord
#main.cpp#include <iostream>int main(){std::cout << "hello word" << std::endl; }
2、步骤二,写CMakeLists.txt
#CMakeLists.txtproject (HELLO)set(SRC_LIST main.cpp)message(STATUS "This is BINARY dir " ${HELLO_BINARY_DIR})message(STATUS "This is SOURCE dir "${HELLO_SOURCE_DIR})add_executable(hello ${SRC_LIST})
3、步骤三、使用cmake,生成makefile文件
cmake .输出:[root@localhost cmake]# cmake .CMake Warning (dev) in CMakeLists.txt:Syntax Warning in cmake code at/root/cmake/CMakeLists.txt:7:37Argument not separated from preceding token by whitespace.This warning is for project developers. Use -Wno-dev to suppress it.-- The C compiler identification is GNU 10.2.1-- The CXX compiler identification is GNU 10.2.1-- 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-- 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-- This is BINARY dir /root/cmake-- This is SOURCE dir /root/cmake-- Configuring done-- Generating done-- Build files have been written to: /root/cmake
目录下就生成了这些文件-CMakeFiles, CMakeCache.txt, cmake_install.cmake 等文件,并且生成了Makefile.
现在不需要理会这些文件的作用,以后你也可以不去理会。最关键的是,它自动生成了Makefile.
4、使用make命令编译
root@localhost cmake]# makeScanning dependencies of target hello[100%] Building CXX object CMakeFiles/hello.dir/main.cpp.oLinking CXX executable hello[100%] Built target hello
