C/C++ project builder updater
Project description
C/C++ project builder updater
Command-line tool for setting up and maintaining C/C++ project build systems. Based on Makefile, provides VSCode support, and designed for CI/CD workflows.
Key Features
- make-based - built on Makefile with minimal external dependencies
- embedded projects focused - for embedded development while also supporting desktop environments
- separation of concerns - strict separation of all scripts and configurations into three segments:
core,project, andworkspace - IDE independent - build process does not require any specific IDE
- multi-platform support - supports building on both Windows and Linux
- VSCode support - VSCode is the primary supported editor
- CI/CD support - includes ready-to-use configs for CI/CD pipelines
- header section - utilities for generating and using header with project metadata (including data extracted from the Git repository)
Installation
pip install builder-updater
Running
Once installed, you can run the tool from the command line.
builder_updater
Command‑Line Options
-p,--path<project_path>Specifies the path to the target project directory (defaults to the current directory).-f,--forceForces the update of the project, overriding existing configuration files.-c,--cleanCleans old files in the project directory before performing the update.-e,--exampleCopies example source files into the project directory.-i,--infoRecursive scan and displays information about projects (--pathis root of scan).-h,--helpShows the help message with a summary of all available options and exits.--versionPrints the current version of thebuilder-updaterpackage and exits.--builder-versionPrints the version of thebuilderand exits.
Component Description
-
Core of the makefile-based build system:
-
makefile- the top-level entry point of the build system. It assembles a list of build configurations based on filenames located inproject_configs/build_configs. For each discovered configuration, it invokes the build scriptbuild_scripts/builder.mk. The targets defined in this script also allow building each configuration individually. See the file contents and inline comments for detailed information. -
build_scripts/builder.mk- the main build script. Contains all required targets and mechanisms that implement recursive discovery and compilation of source files. The list of search directories is configured inproject_configs/common.mk(shared for all build configurations) andproject_configs/build_configs/<bc_name>.mk(specific to each configuration). Refer to the file contents and comments for details. -
build_scripts/global.mk- provides global variables, including platform-specific ones for different operating systems. -
build_scripts/env_default.mk- default environment settings. To configure a local environment, create a fileproject_configs/env.mk(see below).
-
-
Build configuration:
-
project_configs/common.mk- a set of common project settings and parameters. Includes toolchain selection, additional build flags, source directories, static library paths, and more. -
project_configs/build_configs/<bc_name>.mk- settings and parameters for the corresponding build configuration. The filename is automatically detected by the top-levelmakefileand used as the configuration name. At least one build configuration file must exist.
-
-
CI/CDconfiguration:-
build_scripts/gitlab-ci-builder.yml- defines the primary GitLab CI stages required to build the project. -
project_configs/gitlab-ci-project.yml- project-specific environment variables and CI/CD stages used during pipeline execution. -
gitlab-ci.yml- combinesbuild_scripts/gitlab-ci-builder.ymlandproject_configs/gitlab-ci-project.ymlinto a unified project configuration.
-
-
Executable file header:
-
build_scripts/bin_header/bin_header.h- header structure definition for use within the project’s source code. -
build_scripts/bin_header/bin_header.c- contains the header instance. To embed it into the executable, include this file in the project’s.csource list. -
build_scripts/post_build/modify_header.py- a script that injects project information into the header (including Git repository state) and computes CRC. -
build_scripts/crc_soft/crc_soft.h- header file of the CRC calculation module used to verify header and firmware integrity; also includes table generators. -
build_scripts/crc_soft/crc_soft.c- implementation of the CRC module, including constant tables for IEEE 802.3 CRC-32 and CCITT CRC-16.
-
-
VSCodeeditor configuration:-
.vscode/c_cpp_properties.json- configuration for the VSCode C/C++ extension, including the path tocompile_commands.json. -
.vscode/launch.json- debugger launch configuration for VSCode (F5). -
.vscode/settings.json- general VSCode editor settings. -
.vscode/tasks.json- build task configuration for VSCode (Ctrl + Shift + B).
-
-
Environment files (created by the user):
-
project_configs/env.mk- environment configuration formakefile, specific to the user’s workspace (compiler paths, OpenOCD path, etc.). Version control tracking is disabled for this file to avoid conflicts between different user environments. -
<name>.code-workspace- VSCode workspace configuration. Version control tracking is disabled for this file for the same reason.
-
-
Miscellaneous:
-
.gitignore- list of file patterns ignored bygit. -
output/compile_commands.json- generated during the build (not stored in git). Used by the editor to provide correct syntax and preprocessing insights, including parameters defined in.mkfiles. -
build_scripts/post_build/gcc_map_parser.py- parser for.mapfiles, used to analyze the largest modules, memory usage, etc. (in development).
-
Adding the Build System to a New or Existing Project
-
The target project must be prepared for updating the build system in advance - all changes must be saved, or (for projects without version control) copied to another directory.
-
Run the build-system installation script (when launched from the project directory, the
--pathargument is optional):builder_updater --path <project_path> --force
-
Configure the files
project_configs/common.mkandproject_configs/build_configs/<bc_name>.mk(see comments for variable descriptions). -
Create and configure the file
project_configs/env.mkbased on the template inbuild_scripts/env_default.mk. -
Create and configure the
<name>.code-workspacefile based on the following template:{ "folders": [ { "path": "." } ], "settings": { "prjCfg.svdPath": "${workspaceFolder}\\STM32F103.svd", // path to the MCU peripheral description file "prjCfg.gdbPath": "arm-none-eabi-gdb", // path to the gdb debugger (or command if added to the `PATH` environment variable) "prjCfg.ocdPath": "openocd", // path to openocd (or command if added to the `PATH` environment variable) "prjCfg.ocdPort": "3333", // port for gdb to connect to openocd "prjCfg.ocdAddr": "localhost", // IP address or hostname of the openocd server for remote debugging "prjCfg.ocdInterface": "interface/stlink.cfg", // path to the interface `.cfg` file (debug probe) "prjCfg.ocdTarget": "target/stm32f1x.cfg", // path to the target `.cfg` file (micro-controller) "prjCfg.ocdUserCmd": "", // custom openocd startup command "prjCfg.pythonPath": "python3" // path to the Python interpreter } }
-
.vscode/settings.json- configure the compiler version and select the target architecture. -
.vscode/tasks.json- list all project configuration names insideinputs.options. -
.vscode/launch.json- list relative paths to executable files (relative to theoutputdirectory) insideinputs.options. -
project_configs/gitlab-ci-project.yml- specify the container image used by the project in the variableGITLAB_DOCKER_IMAGE. -
To enable automatic header generation, add the following template to the project's linker script (and adjust if necessary):
.header (READONLY): { . = ALIGN(4); KEEP(*(.header)) . = ALIGN(4); } > FLASH PROVIDE(header_load_addr = ORIGIN(FLASH)); PROVIDE(header_boot_addr = Reset_Handler); PROVIDE(header_firmware_size = LOADADDR(.data) + SIZEOF(.data) - header_load_addr);
Updating Non-Breaking Changes of the Build System
- Run the build system update script:
builder_updater -p <project_path>
Updating BREAKING Changes of the Build System
-
Run the build system update script:
builder_updater -p <project_path> -f -c
-
Since
--forcemode overwrites all configuration files, you must manually restore your project-specific settings while taking into account changes introduced in the build system (automation is under development). Files requiring manual adjustments:project_configs/common.mkproject_configs/build_configs/<bc_name>.mkproject_configs/gitlab-ci-project.yml
C/C++ project builder updater
Инструмент для настройки и обновления системы сборки C/C++ проектов. Построен на базе Makefile, включает поддержку VSCode и ориентирован на использование в CI/CD.
Ключевые особенности
- make-based - построен на Makefile с минимизацией дополнительных зависимостей
- embedded projects focused - ориентировано на embedded проекты, но поддерживает и desktop
- separation of concerns - строгое разделение всех скриптов и конфигураций на 3 сегмента:
core,project,workspace - IDE independent - сборка не требует обязательного использования IDE
- multi-platform support - поддержка сборки в Windows и Linux
- VSCode support - основной поддерживаемый редактор VSCode
- CI/CD support - готовый инструментарий для CI/CD
- header section - инструменты формирования секции заголовка с информацией о проекте (в том числе из git репозитория)
Установка
pip install builder-updater
Запуск
builder_updater
Параметры запуска
-p,--path<project_path>Путь к целевой директории проекта (по умолчанию — текущая директория).-f,--forceВыполняет принудительное обновление проекта, перезаписывая существующие конфигурационные файлы.-c,--cleanОчищает старые файлы в директории проекта перед обновлением.-e,--exampleКопирует пример исходных файлов в директорию проекта.-i,--infoРекурсивно сканирует и выводит информацию о проектах (--pathиспользуется как корень сканирования).-h,--helpПоказывает справку со сводкой всех доступных опций и завершает работу.--versionВыводит текущую версию пакетаbuilder-updaterи завершает работу.--builder-versionВыводит версиюbuilderи завершает работу.
Описание компонентов
-
Ядро makefile-based сборки:
-
makefile- верхний уровень системы сборки. Формирует список конфигураций по названиям файлов, расположенных в папкеproject_configs/build_configs. По сформированному списку запускает сборкуbuild_scripts/builder.mkдля каждой конфигурации. Также по сформированным в этом скрипте целям можно запустить сборку каждой конфигурации по отдельности. Подробнее смотри содержимое файла и приведенные в нем комментарии. -
build_scripts/builder.mk- основной скрипт сборки. Содержит все необходимые описания целей и механизмов, реализующих рекурсивный поиск и компиляцию исходных файлов. Список директорий для поиска настраивается в файлахproject_configs/common.mk(общие для всех конфигураций сборки) иproject_configs/build_configs/<bc_name>.mk(для соответствующей конфигурации). Подробнее смотри содержимое файлов и приведенные в нем комментарии. -
build_scripts/global.mk- содержит общие глобальные переменные, в том числе различающиеся в разных операционных системах. -
build_scripts/env_default.mk- настройки окружения по умолчанию. Для настройки локального окружения необходимо создать файлproject_configs/env.mk(см. подробнее ниже).
-
-
Конфигурация сборки:
-
project_configs/common.mk- набор общих настроек и параметров проекта. Включает в себя наименование тулчейна, дополнительные флаги сборки, расположение исходников, статических библиотек и пр. -
project_configs/build_configs/<bc_name>.mk- настройки и параметры соответствующих конфигураций. Наименование файла автоматически подхватывается скриптомmakefileи далее используется как название конфигурации. Должен существовать минимум один файл конфигурации сборки.
-
-
Описание
CI/CD:-
build_scripts/gitlab-ci-builder.yml- основныеstages, необходимые для сборки проекта. -
project_configs/gitlab-ci-project.yml- специфичные для проекта переменные окружения иstages, используемые при сборке черезCI/CD. -
gitlab-ci.yml- комбинирует конфигурацииbuild_scripts/gitlab-ci-builder.ymlиproject_configs/gitlab-ci-project.ymlв общую для проекта.
-
-
Заголовок исполняемого файла
-
build_scripts/bin_header/bin_header.h- описание структуры заголовка для использования в исходном коде проекта. -
build_scripts/bin_header/bin_header.c- содержит инстанс заголовка. Для его инъекции в исполняемый файл необходимо добавить этот файл в список.cисходников проекта. -
build_scripts/post_build/modify_header.py- скрипт для добавления в заголовок информации о состоянииgitрепозитория проекта и расчета CRC. -
build_scripts/crc_soft/crc_soft.h- заголовочный файл модуля вычисления CRC для контроля целостности заголовка и ВПО, также содержит генераторы таблиц. -
build_scripts/crc_soft/crc_soft.с- исходный код модуля вычисления CRC, дополнительно содержит const таблицы для IEEE 802.3 CRC-32 и CCITT CRC-16
-
-
Конфигурация редактора
VSCode-
.vscode/c_cpp_properties.json- настройки плагина С/C++ для VSCode, в том числе путь к файлуcompile_commands.json. -
.vscode/launch.json- настройки запуска отладчика в VSCodeF5. -
.vscode/settings.json- общие настройки редактора VSCode. -
.vscode/tasks.json- настройки запуска сборки в VSCodeCtrl + Shift + B.
-
-
Файлы окружения (создаются пользователем)
-
project_configs/env.mk- содержит конфигурацию окружения дляmakefile, специфичную для конкретного рабочего пространства (путь к компилятору, openocd и т.п.). Для файла отключено отслеживание системой контроля версийgitдля избежания конфликтов настроек разных окружений. -
<name>.code-workspace- содержит конфигурацию workspaceVSCode. Для файла отключено отслеживание системой контроля версийgitдля избежания конфликтов настроек разных окружений.
-
-
Остальное:
-
.gitignore- список шаблонов файлов, игнорируемыхgit. -
output/compile_commands.json- создается в процессе сборки (не сохраняется в git). Позволяет корректно формировать подсветку синтаксиса и препроцессора в том числе для параметров, задаваемых в файлах.mk. -
build_scripts/post_build/gcc_map_parser.py- парсер.mapфайла для анализа самых объемных модулей, использования памяти и пр. (в разработке).
-
Добавление системы сборки в новый или существующий проект
-
Целевой проект должен быть предварительно подготовлен к обновлению системы сборки - все изменения сохранены или (для проектов без контроля версии) скопированы в другую папку.
-
Запустить скрипт добавления системы сборки (при запуске из директории проекта аргумент
--pathуказывать не обязательно):builder_updater --path <project_path> --force
-
Заполнить файлы
project_configs/common.mkиproject_configs/build_configs/<bc_name>.mk(см. комментарии к переменным). -
Создать и заполнить файл
project_configs/env.mkпо шаблону изbuild_scripts/env_default.mk. -
Создать и заполнить файл
<name>.code-workspaceпо шаблону:{ "folders": [ { "path": "." } ], "settings": { "prjCfg.svdPath": "${workspaceFolder}\\STM32F103.svd", // путь к файлу с описанием периферии контроллера "prjCfg.gdbPath": "arm-none-eabi-gdb", // путь к отладчику gdb (или команда вызова, если путь указан в переменной окружения `PATH`) "prjCfg.ocdPath": "openocd", // путь к openocd (или команда вызова, если путь указан в переменной окружения `PATH`) "prjCfg.ocdPort": "3333", // порт для подключения gdb к openocd "prjCfg.ocdAddr": "localhost", // ip адрес или hostname сервера openocd для удаленного подключения "prjCfg.ocdInterface": "interface/stlink.cfg", // путь к `.cfg` файлу интерфейса (программатора) "prjCfg.ocdTarget": "target/stm32f1x.cfg", // путь к `.cfg` файлу таргета (микроконтроллера) "prjCfg.ocdUserCmd": "", // пользовательская команда запуска openocd "prjCfg.pythonPath": "python3", // путь к интерпретатору python } }
-
В файле
.vscode/settings.jsonнастроить версию компилятора и выбрать архитектуру. -
В файле
.vscode/tasks.jsonв спискеinputs.optionsперечислить названия конфигураций проекта -
В файле
.vscode/launch.jsonв спискеinputs.optionsперечислить относительные пути к исполняемым файлам (относительно папкиoutput). -
В файле
project_configs/gitlab-ci-project.ymlуказать используемый образ контейнера в переменнойGITLAB_DOCKER_IMAGE. -
Для использования механизма генерации заголовка необходимо добавить в линкер-скрипт проекта шаблон (при необходимости отредактировав):
.header (READONLY): { . = ALIGN(4); KEEP(*(.header)) . = ALIGN(4); } > FLASH PROVIDE(header_load_addr = ORIGIN(FLASH)); PROVIDE(header_boot_addr = Reset_Handler); PROVIDE(header_firmware_size = LOADADDR(.data) + SIZEOF(.data) - header_load_addr);
Обновление не ломающих изменений системы сборки
- Запустить скрипт обновления системы сборки:
builder_updater -p <project_path>
Обновление ЛОМАЮЩИХ изменений системы сборки
-
Запустить скрипт обновления системы сборки:
builder_updater -p <project_path> -f -с
-
Так как в режиме
--forceскрипт перезаписывает все конфигурационные файлы, необходимо вручную восстановить настройки с учетом изменений системы сборки (автоматизация будет дорабатываться). Список файлов требующих ручного исправления:project_configs/common.mkproject_configs/build_configs/<bc_name>.mkproject_configs/gitlab-ci-project.yml
Задачи в части доработок следующей версии
- Внести исправления в интерфейс
crc_soft - Расширить файл
env.mkи добавить генерацию<name>.code-workspaceна его основе - Возможно добавить алгоритм авто-заполнения inputs в
tasks.jsonиlaunch.json
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file builder_updater-0.1.0a1.tar.gz.
File metadata
- Download URL: builder_updater-0.1.0a1.tar.gz
- Upload date:
- Size: 41.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6a44c0fb6dd031fddcc07d71323870ad3bb126da3c5d4c7f0a76135eb2f10528
|
|
| MD5 |
52ae497e97fc09057ee5dc9e82748b70
|
|
| BLAKE2b-256 |
a03a0be2ddbbfb4f8627a1d1f6149f44bbe42c2efe0b13f91bd7a56ab794e230
|
File details
Details for the file builder_updater-0.1.0a1-py3-none-any.whl.
File metadata
- Download URL: builder_updater-0.1.0a1-py3-none-any.whl
- Upload date:
- Size: 42.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b0a56fddffb13d2325c9904eb54ff2829160ce92af723008a864f5b2522516b1
|
|
| MD5 |
a23fca07eff162ff018dd593a4290b09
|
|
| BLAKE2b-256 |
2283582e64b8a99b94c6e187b4c62ed3c9309f5208268745d9cad446f878a92e
|