目标:
创建一个工程,工程里面包含了程序的源码,库的源码。我们先编译出库,然后再编译程序并链接我们刚编译出来的库。同时将程序、库文件放到指定位置。
目录结构:
lqd@ubuntu:~/lqd/cmake/test$ tree
.
├── build
├── CMakeLists.txt
├── inc
├── lib
│ ├── CMakeLists.txt
│ ├── sum.c
│ └── sum.h
└── src
├── CMakeLists.txt
└── main.c
4 directories, 6 files
各个文件内容如下:
/home/lqd/lqd/cmake/test/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.1)
PROJECT(demo1)
ADD_SUBDIRECTORY(./lib)
ADD_SUBDIRECTORY(./src)
/home/lqd/lqd/cmake/test/lib/CMakeLists.txt
#CMAKE_MINIMUM_REQUIRED(VERSION 3.1)
#set LIBRARY_OUTPUT_PATH 设置库文件的输出路径
#PROJECT_BINARY_DIR 永远执行cmake命令执行的目录
#将生成的库文件放到执行cmake目录下面的out/lib目录下
#如果执行cmake目录下面没有out/lib目录,那么会自己去创建out/lib目录
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/out/lib)
aux_source_directory(./ DIR_LIB_SRCS)
#add_library(sum SHARED ${DIR_LIB_SRCS})
add_library(sum STATIC ${DIR_LIB_SRCS})
/home/lqd/lqd/cmake/test/lib/sum.c
#include "sum.h"
int sum(int a, int b)
{
int sum;
sum = a + b;
return sum;
}
/home/lqd/lqd/cmake/test/lib/sum.h
#ifndef _SUM_H_
#define _SUM_H_
int sum(int a, int b);
#endif
/home/lqd/lqd/cmake/test/src/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.1)
#PROJECT_SOURCE_DIR 指向包含PROJECT的CMakeLists.txt的目录
#INCLUDE_DIRECTORIES 导入我们要包含的头文件路径
INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/lib)
#set EXECUTABLE_OUTPUT_PATH设置可执行程序的输出路径
#PROJECT_BINARY_DIR 执行cmake执行的目录
#将可执行程序放到 cmake执行的目录下面的out/bin目录
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/out/bin)
aux_source_directory(./ DIR_LIB_SRCS)
ADD_EXECUTABLE(main ${DIR_LIB_SRCS})
TARGET_LINK_LIBRARIES(main sum)
/home/lqd/lqd/cmake/test/src/main.c
#include <stdio.h>
#include "sum.h"
int main(int argc, char *argv[])
{
int result = 0;
printf("Hello worlod.\n");
result = sum(1, 2);
printf("result=%d \n", result);
return 0;
}
进入到build目录,即/home/lqd/lqd/cmake/test/build目录
执行命令:cmake ../
执行命令:make
这个时候,我们的目标文件就生成了。out对应的目录结构:
lqd@ubuntu:~/lqd/cmake/test/build$ tree out/
out/
├── bin
│ └── main
└── lib
└── libsum.a
2 directories, 2 files