1# RT-Thread package.json 构建支持 2 3## 概述 4 5RT-Thread支持使用package.json来定义组件的构建配置,作为传统SConscript的简化替代方案。 6 7## 现有支持 8 9### package.json格式 10```json 11{ 12 "name": "hello", 13 "description": "Hello World component for RT-Thread", 14 "type": "rt-thread-component", 15 "dependencies": ["RT_USING_HELLO"], 16 "defines": [], 17 "sources": [{ 18 "name": "src", 19 "dependencies": [], 20 "includes": ["."], 21 "files": ["hello.c"] 22 }] 23} 24``` 25 26### 字段说明 27- **name**: 组件名称(必需) 28- **type**: 必须为"rt-thread-component"(必需) 29- **description**: 组件描述 30- **dependencies**: 全局依赖,数组形式的宏定义 31- **defines**: 全局宏定义 32- **sources**: 源文件组数组,每组可包含: 33 - **name**: 源组名称 34 - **dependencies**: 源组特定依赖 35 - **includes**: 头文件搜索路径 36 - **files**: 源文件列表(支持通配符) 37 38## 使用方式 39 40### 1. 在SConscript中使用 41 42方式一:使用PackageSConscript(推荐) 43```python 44from building import * 45 46objs = PackageSConscript('package.json') 47Return('objs') 48``` 49 50方式二:直接调用BuildPackage 51```python 52Import('env') 53from package import BuildPackage 54 55objs = BuildPackage('package.json') 56Return('objs') 57``` 58 59### 2. 目录结构示例 60``` 61mycomponent/ 62├── SConscript 63├── package.json 64├── mycomponent.c 65├── mycomponent.h 66└── src/ 67 └── helper.c 68``` 69 70### 3. 完整示例 71 72package.json: 73```json 74{ 75 "name": "mycomponent", 76 "description": "My RT-Thread component", 77 "type": "rt-thread-component", 78 "dependencies": ["RT_USING_MYCOMPONENT"], 79 "defines": ["MY_VERSION=1"], 80 "sources": [ 81 { 82 "name": "main", 83 "dependencies": [], 84 "includes": ["."], 85 "files": ["mycomponent.c"] 86 }, 87 { 88 "name": "helper", 89 "dependencies": ["RT_USING_MYCOMPONENT_HELPER"], 90 "includes": ["src"], 91 "files": ["src/*.c"] 92 } 93 ] 94} 95``` 96 97## 工作原理 98 991. **依赖检查**:首先检查全局dependencies,如果不满足则跳过整个组件 1002. **源组处理**:遍历sources数组,每个源组独立检查dependencies 1013. **路径处理**:includes相对路径基于package.json所在目录 1024. **文件匹配**:使用SCons的Glob函数处理文件通配符 1035. **构建调用**:最终调用DefineGroup创建构建组 104 105## 与DefineGroup的对比 106 107| 特性 | package.json | DefineGroup | 108|------|--------------|-------------| 109| 配置方式 | JSON文件 | Python代码 | 110| 依赖管理 | 结构化 | 函数参数 | 111| 源文件组织 | 分组管理 | 单一列表 | 112| 条件编译 | 源组级别 | 整体级别 | 113| 灵活性 | 中等 | 高 | 114| 易用性 | 高 | 中等 | 115 116## 最佳实践 117 1181. **简单组件优先使用package.json**:配置清晰,易于维护 1192. **复杂逻辑使用SConscript**:需要动态逻辑时使用传统方式 1203. **混合使用**:可以在同一项目中混用两种方式 121 122## 注意事项 123 1241. package.json必须是有效的JSON格式 1252. type字段必须为"rt-thread-component" 1263. 文件路径相对于package.json所在目录 1274. 依赖不满足时会静默跳过,不会报错 1285. 与RT-Thread构建系统完全集成,不支持独立构建