cmake 学习
什么是cmake?
百度官方: CMake 是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。他能够输出各种各样的 Makefile 或者 project 文件,CMake 并不直接建构出最终的软件,而是产生标准的建构档(如 Makefile 或 projects)。C/C++的编译工具之前用的是 g++
如何使用?
参考:链接 Windows和Linux下都可以使用,本次演示为Ubuntu环境下g++编译
1、安装g++apt install g++
2、新建test.c
vim test.c #includeint main(void) { printf("Hello, world!\n"); return 0; }
3、编译文件
g++ test.c -o test
4、运行
./test
cmake 编译
1、安装cmake
apt install cmake
2、编写程序
(1)创建文件/文件夹
mkdir helloworld cd helloworld mkdir bin lib src include build touch CMakeLists.txt
(2)、进入Src目录,新建源文件
cd src touch main.cpp helloworld.cpp
(3)、返回上级目录,进入include目录,新建头文件
cd ../include/ touch helloworld.h
(4)、对源文件和头文件进行编写并保存
// main.cpp #includeint main() { helloworld obt; obt.outputWord(); return 0; } // helloworld.cpp #include "helloworld.h" void helloworld::outputWord() { std::cout << "hello world!" << std::endl; } // helloworld.h #ifndef HELLOWORLD_H_ #define HELLOWORLD_H_ #include class helloworld { public: void outputWord(); }; #endif
(5)、编写CMakeLists.txt文件
#cmake最低版本以及工程名称
cmake_minimum_required(VERSION 2.8)
project(helloworld)
#设置编译方式(“debug”与“Release“)
SET(CMAKE_BUILD_TYPE Release)
#设置可执行文件与链接库保存的路径
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib)
#设置头文件目录使得系统可以找到对应的头文件
include_directories(
${PROJECT_SOURCE_DIR}/include
)
#选择需要编译的源文件,凡是要编译的源文件都需要列举出来
add_executable(helloworld src/helloworld.cpp src/main.cpp)
(6)、编译
cd build cmake .. make
(7)、运行
ls bin ./helloworld