esp-idf使用cmake完成工程构建,故先学习cmake的使用
1.cmake基本知识
#约束cmake最低版本
cmake_minimum_required(VERSION 3.10)
#设置工程名称
project(projectName)
#单文件时直接编译即可
add_executable(可执行文件名称 源文件)
eg:
add_executable(main main.cpp)
#很多源文件,使用aux_source_directory函数
aux_source_directory(源文件地址 变量)
eg:
aux_source_directory(./source SCR_LIST)
add_executable(main ${SCR_LIST})
#头文件不在一个文件夹
include_directories(头文件文件夹地址)
eg:
include_directories(./include)
aux_source_directory(./source1 SRC_LIST2)
add_executable(hello ${SRC_LIST2})
内置变量${PROJECT_BINARY_DIR}表明执行cmake的目录
2.esp-idf构建系统
首先esp-idf构建系统的CMakeLists.txt分为两类,一类是项目CMakeList文件,处于项目顶层,一类是组件CMakeList文件。以初始的hello_world项目为例。
项目目录结构
首先是顶层CMakeLists.txt文件,也是最小项目CMakeLists.txt文件
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(hello_world)
这里引用官方文档的解释
-
cmake_minimum_required(VERSION 3.16)
必须放在 CMakeLists.txt 文件的第一行,它会告诉 CMake 构建该项目所需要的最小版本号。ESP-IDF 支持 CMake 3.16 或更高的版本。 -
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
会导入 CMake 的其余功能来完成配置项目、检索组件等任务。 -
project(myProject)
会创建项目本身,并指定项目名称。该名称会作为最终输出的二进制文件的名字,即myProject.elf
和myProject.bin
。每个 CMakeLists 文件只能定义一个项目
其次是组件CMakeLists.txt文件,也是最小组件CMakeLists.txt文件
idf_component_register(SRCS "hello_world_main.c"
INCLUDE_DIRS "")
- 使用idf_component_register将组件添加到构建系统。
- SRCS 源文件列表
- INCLUDE_DIRS 头文件目录,hello_world例程中没有其他头文件,故为空。
- 其次可能还有REQUIRES 说明组件依赖。
学习验证
手动构建目录以及填写相关CMakeLists.txt文件,使用esp-idf进行构建
如图构建如下目录工程
add.h
int add(int a,int b);
add.c
#include "add.h"
int add(int a, int b) {
return a + b;
}
add组件的CMakeLists.txt
idf_component_register(SRCS "add.c"
INCLUDE_DIRS "./include")
main.c
#include <stdio.h>
#include "add.h"
void app_main(void){
printf("%d%s",add(3,5),"Hello World!");
}
main组件的CMakeLists.txt
idf_component_register(SRCS "main.c"
INCLUDE_DIRS "")
根据官方文档的说法:main
组件比较特别,因为它在构建过程中自动依赖所有其他组件。所以不需要向这个组件传递 REQUIRES
或 PRIV_REQUIRES
。所以尽管main组件依赖add组件,但还是没有添加进REQUIRES。
项目顶层CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(project_by_hand)
编译烧录代码,并通过串口查看结果。看自己连接的是哪个端口,不一定是COM16。
idf.py set-target esp32s3
idf.py build
idf.py -p COM16 flash
idf,py -p COM16 monitor
实验成功!
12.15补充
官方文档中关于通用组件依赖的描述:
通用组件依赖项
为避免重复性工作,各组件都用自动依赖一些“通用”IDF 组件,即使它们没有被明确提及。这些组件的头文件会一直包含在构建系统中。
通用组件包括:cxx、newlib、freertos、esp_hw_support、heap、log、soc、hal、esp_rom、esp_common、esp_system。