本例演示使用cmake编译一个可执行程序,并指定可执行程序的生成目录。
示例目录结构
|-- build
|-- CMakeLists.txt
|-- inc # 头文件目录
| `-- add.h
|-- lib
|-- out # 可执行程序生成目录
`-- src # 源文件目录
|-- add.c
`-- main.c
add.c
#include "add.h"
int add(int a, int b)
{
return (a+b);
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "add.h"
int main(int argc, char** argv)
{
int a = 1;
int b = 2;
printf("%d+%d=%d\n", a, b, add(a,b));
return 0;
}
CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
cmake_policy(SET CMP0048 NEW)
project(test03 VERSION "1.2.3.4")
include_directories(./inc) # 指定头文件搜索路径,相当gcc的 -I
aux_source_directory(./src dir_srcs) # 获取源码文件
#message(${dir_srcs}) 可以打开注释查看dir_srcs中所包含的文件路径
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ../out) # 指定可执行程序的输出目录
add_executable(add ${dir_srcs}) # 生成可执行程序
如果你看过前一篇文章,除了第6行和第11行外,其他的应该都知道其作用(PS:如果不清楚就看前一篇文章)。接下来重点解释第6行和第11行。
include_directories()
include_directories([AFTER|BEFORE] [SYSTEM] dir1 [dir2 ...])
Add the given directories to those the compiler uses to search for include files. Relative paths are interpreted as relative to the current source directory.
指定头文件搜索路径,相当gcc的 -I。你可以在build/CMakeFiles/add.dir/flags.make中发现C_INCLUDES = -I/your_path/./inc
,即是通过include_directories(./inc)
得到的。
AFTER|BEFORE
即是控制头文件目录的添加顺序。例如,在调用include_directories命中之前,头文件的搜索路径是/usr/include;/usr/local/include
,现在要新添加一个搜索路径/home/yudao/test/inc
;如果指定AFTER
(默认方式),那么就是在现有搜索路径进行追加(尾插),就变成/usr/include;/usr/local/include;/home/yudao/test/inc
;如果指定BEFORE
,那么就是在现有搜索路径进行前添加(头插),就变成/home/yudao/test/inc;/usr/include;/usr/local/include
;如果指定SYSTEM
,那么将添加的路径作为系统搜索路径。通常在编码时,系统搜索路径的头文件使用#include<>
来包含,用户指定搜索路径的头文件使用#include ""
来包含。
CMAKE_RUNTIME_OUTPUT_DIRECTORY
Where to put all the RUNTIME target files when built.
CMAKE_RUNTIME_OUTPUT_DIRECTORY是cmake的变量(variable),通过set()命令来指定’RUNTIME target files’的输出路径,'RUNTIME target files’可以理解为可执行文件。
set()
Set a normal, cache, or environment variable to a given value
说白了就是给变量赋值。
编译
cd build
cmake ..
make
最终会在out目录下生成一个add可执行程序。
执行 ./add 会打印 1+2=3