背景:
转自:http://blog.youkuaiyun.com/yaked/article/details/49388715
参考网址:http://blog.youkuaiyun.com/wokaowokaowokao12345/article/details/50414468
1. 简单的利用CMakeLists.txt来自动编译程序
我们的程序源文件为main.cpp。放在目录CMake_learning/src下
- #include<iostream>
- int main()
- {
- std::cout<<"Hello world!"<<std::endl;
- return 0;
- }
为了编译该程序,我们的CMakeLists.txt如下
- project(main)
- cmake_minimum_required(VERSION 2.8 FATAL_ERROR)
- aux_source_directory(./src DIR_SRCS)
- add_executable(main ${DIR_SRCS})
第三行将当前目录所有的源文件都赋值给了DIR_SRCS。一般三、四行直接合并为一句
- add_executable(main src/main.cpp)
整个程序的目录结构如下
然后进入build文件夹,cmake .. 然后make
2. 程序链接自己创建的库
在src目录下新建两个文件,一个是hello_world.h
- #ifndef __HELLO_WORLD_H
- #define __HELLO_WORLD_H
- void say_hello();
- #endif
另一个是hello_world.cpp
- #include <iostream>
- void say_hello()
- {
- std::cout<<"Hello Yake!"<<std::endl;
- }
main.cpp修改如下
- #include"hello_world.h"
- int main()
- {
- say_hello();
- return 0;
- }
CMakeLists.txt
- cmake_minimum_required(VERSION 2.8)
- project(main_with_lib)
- # Define a library target called hello_world
- add_library(hello_world src/hello_world.cpp)
- add_executable(main_with_lib src/main.cpp)
- target_link_libraries(main_with_lib hello_world )
运行结果如下
要注意的是生成了一个链接库libhello_world.a