0 cmake安装与卸载
apt-get 方式
sudo apt-get install cmake
cmake卸载
sudo apt-get autoremove cmake
1 创建简单实例
1.1 文件列表
1.2 最外层目录下CMakeList.txt内容
cmake_minimum_required(VERSION 2.8.3)
# 工程名
project(CmakeDemo)
# 添加块目录
# set(HELLO_SRC hello/hello.cpp)
# set(WORLD_SRC world/world.cpp)
# 添加编译目录并执行目录下CMakeList.txt文件
add_subdirectory(hello)
add_subdirectory(world)
add_subdirectory(src)
1.3 hello目录下各文件内容
CMakeList.txt
# 编译生成静态链接库
add_library(hello hello.cpp)
hello.h
#ifndef HELLO_H
#define HELLO_H
#include <iostream>
using namespace std;
void myhello();
#endif
hello.cpp
#include "hello.h"
void myhello()
{
cout <<"hello*****"<<endl;
}
1.4 world目录下文件内容
CMakeList.txt
#将当前的源文件名字都添加到DIR_WORLD_SRCS变量下
aux_source_directory(. DIR_WORLD_SRCS)
add_library(world ${DIR_WORLD_SRCS})
world.h
#ifndef WORLD_H
#define WORLD_H
#include <iostream>
using namespace std;
void myworld();
#endif
world.cpp
#include "world.h"
void myworld()
{
cout <<"world!"<<endl;
}
1.5 src目录下内容
CMakeList.txt
# 包含hello,world头文件目录,PROJECT_SOURCE_DIR为工程目录
include_directories(${PROJECT_SOURCE_DIR}/hello)
include_directories(${PROJECT_SOURCE_DIR}/world)
# 生成可执行文件为main
add_executable(main main.cpp)
# 链接生成目标文件 main
target_link_libraries(main
hello world)
# 设置可执行文件生成到目录lib中
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin/)
main.cpp
#include "hello.h"
#include "world.h"
int main()
{
myhello();
myworld();
cout<<"output success"<<endl;
return 0;
}
2 编译过程
# 最外层CMakeList.txt目录下
mkdir build
cd build
cmake ..
make
bin目录下,生成可执行文件main
3 运行结果
cd bin
./main
运行结果