#1) 项目工程文件目录结构
#2) 源码
##2.1) hello/include/hello.h
#ifndef HELLOWORLD_HELLO_H
#define HELLOWORLD_HELLO_H
extern void hello(void);
#endif //HELLOWORLD_HELLO_H
##2.2) hello/src/hello.c
#include "hello.h"
#include <stdio.h>
void hello()
{
printf("hello.\n");
}
##2.3) hello/CMakeLists.txt
include_directories(./include)
set(DIR_SRCS ./src/hello.c)
add_library(hello SHARED ${DIR_SRCS})
##2.4) world/include/world.h
#ifndef HELLOWORLD_WORLD_H
#define HELLOWORLD_WORLD_H
extern void world(void);
#endif //HELLOWORLD_WORLD_H
##2.5) world/src/world.c
#include "world.h"
#include <stdio.h>
void world()
{
printf("world.\n");
}
##2.6) world/CMakeLists.txt
include_directories(./include)
set(DIR_SRCS ./src/world.c)
add_library(world SHARED ${DIR_SRCS})
##2.7) app/main.c
#include "hello.h"
#include "world.h"
int main()
{
hello();
world();
return 0;
}
##2.8) CMakeLists.txt
cmake_minimum_required(VERSION 3.5)
project(HelloWorld)
set(CMAKE_C_STANDARD 99)
include_directories(hello/include world/include)
set(DIR_SRCS ./app/main.c)
add_subdirectory(hello)
add_subdirectory(world)
add_executable(HelloWorld ${DIR_SRCS})
target_link_libraries(HelloWorld hello world)
#3) 配置
由于顶层目录下CMakeLists.txt包含子目录下的CMakeLists.txt文件,所以只需在顶层目录下运行“cmake .”命令即可。
但“cmake .”执行完毕后,会在工程顶层目录下生成大量cmake输出的临时文件。
我们可以在顶层目录下单独创建一个空目录,专门由于存储cmake配置、make编译输出的文件。使用命令如下:
# cd cmake-build-debug
# cmake ..
# ls
CMakeCache.txt CMakeFiles cmake_install.cmake hello Makefile world
# ls hello/
CMakeFiles cmake_install.cmake Makefile
# ls world/
CMakeFiles cmake_install.cmake Makefile
此时可以看到cmake-build-debug存放很多cmake输出文件,包括工程顶层目录对应的Makefile文件,还有工程子目录下对应的Makefile文件。
#4) 编译
在上面通过cmake输出整个工程编译的Makefile,只需在工程顶层目录下使用命令
make -C cmake-build-debug
执行:
./cmake-build-debug/HelloWorld
#5) 总结
通过上面使用cmake去配置整个项目编译规则,明显感觉比直接去写Makefile要简单很多,而且从工程配置到编译的过程中,整个工程源码目录下不会有其它文件产生,这种做法感觉很优雅,所有的cmake输出文件(包含Makefile),make输出文件(包括*.o/*.a/*.so)都在cmake-build-debug目录下,如果下次想从新配置、编译,只需删除此目录下所有文件和子目录。
最后附上源码:https://download.csdn.net/download/agq358/36493261