如何为复杂多模块项目搭建Meson构建系统(从Makefile移植)
Meson构建配置方案
针对你的项目结构与依赖逻辑,以下是一套简洁的Meson配置方案,既能实现模块合并编译,又能解决Platform与业务模块的耦合问题:
1. 根目录meson.build
project('my_project', 'c', version: '1.0.0', default_options: ['warning_level=3']) # 先构建通用依赖模块 subdir('Common') # 构建Foo业务单元 subdir('Foo') # 构建独立的Bar业务单元 subdir('Bar')
2. Common目录meson.build
将通用代码封装为静态库,统一提供给其他模块依赖:
common_inc = include_directories('inc') common_sources = files( 'src/common_utils.c', # 补充所有Common下的源文件 ) common_lib = static_library('common', common_sources, include_directories: common_inc) common_dep = declare_dependency( include_directories: common_inc, link_with: common_lib )
3. Foo目录meson.build
将Foo/A、Foo/B、Foo/C合并为Foo整体库:
# 引入各子模块 subdir('A') subdir('B') subdir('C') # 合并子模块为Foo整体库 foo_lib = static_library('foo', link_with: [foo_a_lib, foo_b_lib, foo_c_lib], dependencies: common_dep ) foo_dep = declare_dependency( link_with: foo_lib, dependencies: common_dep )
4. Foo/A目录meson.build
核心实现:合并Platform/A与Foo/A代码编译,处理依赖关系:
# 声明当前业务模块的头文件路径 foo_a_inc = include_directories('inc') # 引入Platform/A的源码与头文件(Platform/A依赖Foo/A头文件,需包含foo_a_inc路径) platform_a_inc = include_directories('../../Platform/A/inc') platform_a_sources = files( '../../Platform/A/src/platform_a_driver.c', # 补充所有Platform/A下的源文件 ) # 当前Foo/A的业务源文件 foo_a_sources = files( 'src/foo_a_business.c', # 补充所有Foo/A下的源文件 ) # 合并源码编译为Foo A模块库 foo_a_lib = static_library('foo_a', [foo_a_sources, platform_a_sources], include_directories: [foo_a_inc, platform_a_inc, common_inc], dependencies: common_dep )
5. Foo/B、Foo/C目录meson.build(示例)
若Foo/B依赖Platform/B,参考Foo/A的配置逻辑:
foo_b_inc = include_directories('inc') platform_b_inc = include_directories('../../Platform/B/inc') platform_b_sources = files( '../../Platform/B/src/platform_b_driver.c', ) foo_b_sources = files( 'src/foo_b_business.c', ) foo_b_lib = static_library('foo_b', [foo_b_sources, platform_b_sources], include_directories: [foo_b_inc, platform_b_inc, common_inc], dependencies: common_dep )
6. Bar目录meson.build
与Foo结构一致,合并Bar/A、Bar/B为整体库:
subdir('A') subdir('B') bar_lib = static_library('bar', link_with: [bar_a_lib, bar_b_lib], dependencies: common_dep ) bar_dep = declare_dependency( link_with: bar_lib, dependencies: common_dep )
7. Bar/A目录meson.build
合并Platform/A与Bar/A代码:
bar_a_inc = include_directories('inc') platform_a_inc = include_directories('../../Platform/A/inc') platform_a_sources = files( '../../Platform/A/src/platform_a_driver.c', ) bar_a_sources = files( 'src/bar_a_business.c', ) bar_a_lib = static_library('bar_a', [bar_a_sources, platform_a_sources], include_directories: [bar_a_inc, platform_a_inc, common_inc], dependencies: common_dep )
关键说明
- 合并编译逻辑:通过将Platform模块源码直接加入对应业务模块的源文件列表,实现与业务代码一起编译,满足"Platform/A无法脱离Foo/A单独编译"的要求。
- 依赖封装:使用
declare_dependency统一管理模块的头文件与库依赖,避免重复配置,确保依赖传递正确。 - 独立构建单元:Foo与Bar作为独立子目录,各自管理内部模块,符合项目"Separate build"的需求。
内容的提问来源于stack exchange,提问作者Questor
相关产品推荐
相关产品推荐

