cmake多级目录入门

该博客介绍了如何使用CMake在多目录结构下构建静态库和可执行程序。主要内容包括设置CMakeLists.txt文件,组织项目目录,链接静态库,并通过CMake生成makefile进行编译和运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录结构如下:

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

参考

cmake构建多目录项目

cmake3.0帮助文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值