目录结构如下:
mutil
├── CMakeLists.txt
├── hello
│ ├── CMakeLists.txt
│ ├── hello.c
│ └── hello.h
├── main.c
└── world
├── CMakeLists.txt
├── world.c
└── world.h
mutil目录
mutil下CMakeLists.txt:
#cmake最低版本需求,必须有
cmake_minimum_required(VERSION 3.0)
#项目名称,后面可添加支持的语言,默认是C和C++
project(demo)
#设置hello world 给环境变量TARGET
set(TARGET helloworld)
#把指定目录下所有源代码文件和头文件存入变量DIRSRCS。“.”是指当前目录
aux_source_directory(. DIRSRCS)
#添加头文件目录
include_directories(
${PROJECT_SOURCE_DIR}/hello
${PROJECT_SOURCE_DIR}/world
)
#添加包含CMakeLists.txt和源文件的子目录
add_subdirectory(hello)
add_subdirectory(world)
#使用${DIRSRCS}中的文件生成可执行目标文件 helloworld
add_executable(${TARGET} ${DIRSRCS})
#helloworld 链接静态库hello和world
target_link_libraries(${TARGET} hello world)
main.c
#include <stdio.h>
#include "hello.h"
#include "world.h"
int main()
{
hello();
world();
return 0;
}
hello文件夹
CMakeLists.txt
#把指定目录下所有源代码文件和头文件存入变量DIR_HELLO。“.”是指当前目录
aux_source_directory(. DIR_HELLO)
#从${DIR_HELLO}文件中生成hello库, STATIC是生成静态库
add_library(hello STATIC ${DIR_HELLO})
hello.c
#include <stdio.h>
#include "hello.h"
void hello()
{
printf("hello\n");
}
hello.h
#ifndef HELLO_H
#define HELLO_H
void hello();
#endif
world文件夹
CMakeLists.txt
aux_source_directory(. DIR_WORLD)
add_library(hello STATIC ${DIR_WORLD})
源文件与hello下类似,略。
生成makefile
mutil$ cmake -B build
编译
build目录下编译运行:
build$ make
Scanning dependencies of target world
[ 16%] Building C object world/CMakeFiles/world.dir/world.c.o
[ 33%] Linking C static library libworld.a
[ 33%] Built target world
Scanning dependencies of target hello
[ 50%] Building C object hello/CMakeFiles/hello.dir/hello.c.o
[ 66%] Linking C static library libhello.a
[ 66%] Built target hello
Scanning dependencies of target helloworld
[ 83%] Building C object CMakeFiles/helloworld.dir/main.c.o
[100%] Linking C executable helloworld
[100%] Built target helloworl
build$ ./helloworld