主要讲下cmake是什么东西以及linux下运行cmake的整体框架。cmake是用来产生makefile的一个工具,在执行cmake之前有一个类似makefile的文件CMakeList.txt,在里面进行一系列的描写规则就可以达到编译的结果。
第一步编写一个C++的程序:
#include <iostream>
void hello_world();
上述程序为hello.h文件,主要实现hello_world()函数的声明。
#include "hello.h"
using namespace std;
void hello_world()
{
cout<< "hello world!\n"<<endl;
}
上述程序为hello.cpp文件,主要是调用了hello.h文件,并且实现hello_world()函数功能。
第二步编写主函数:
#include "hello.h"
int main(int argv,char** argr)
{
hello_world();
return 0;
}
上述程序为hello_hello.cpp文件,主要是包含了hello.h文件,并且实现了hello_world()函数的调用。
第三步编写CMakeList.txt文件:
project(hello) //创建一个叫做hello的工程
add_library(hellolib hello.cpp) //添加hello.cpp文件到库中
add_executable(sayhello hello_hello.cpp) //执行hello_hello.cpp 生成sayhello可执行文件
target_link_libraries(sayhello hellolib) //需要把可执行文件连接库,否则会报错,cmake失败
第四步创建build文件:
为了使得工程更加的简洁,我们在hello_hello.cpp所在目录下创建了build文件,进入build文件后执行cmake .. 就可以进行makefile的创建,生成makefile之后执行make 就可以生成可执行文件sayhello。