232 words
1 minute
Using clang-format in Keil: One-Key Formatting for STM32 Projects

When using Keil for STM32 development, updating code through STM32CubeMX often changes generated code to two-space indentation, making the style inconsistent. This tutorial explains how to format code in Keil with a single keyboard shortcut using clang-format.

Prerequisites#

Required components#

  1. Keil uVision IDE
  2. clang-format

Getting clang-format#

Keil V6 users (armclang compiler): The tool is included in the installation directory:

<Keil installation path>\ARM\ARMCLANG\bin\clang-format.exe

Keil V5 users (armcc compiler):

  1. Download the V6 compiler package, Arm Compiler for Embedded 6.24 (for Keil® MDK), from the Arm website.
  2. Extract it into the ARM folder under your Keil installation directory.
  3. Verify the final path:
<Keil installation path>\ARM\ARMCLANG\bin\clang-format.exe

Configuration#

1. Add a custom tool#

  1. Open Keil → Tools → Customize Tools Menu…

    Customize Tools Menu

  2. Click Add to create a new tool.

  3. Configure these fields:

    • Name: clang format

    • Path: the full path to clang-format.exe

    • Arguments:

      -verbose -sort-includes -style=Microsoft -i !E
    • !E refers to the current file.

    • -i modifies the file in place.

2. Set a keyboard shortcut#

  1. Open Edit → Configuration → Shortcut Keys.

  2. Find the “Tools format” entry.

    Shortcut keys

  3. Choose your preferred shortcut. I use Alt + Shift + F, the same shortcut as VSCode.

Usage tips#

  1. Save the file before formatting, because the tool modifies the source file directly.
  2. Formatting applies the Microsoft style to:
    • Code indentation
    • #include ordering
    • Code alignment and other formatting details

Advanced customization#

clang-format supports extensive customization. Adjust the arguments to change:

  • Indentation width
  • Brace style
  • Line wrapping and other rules

For specific formatting requirements, consult the clang-format documentation or relevant technical support.

Tip: This setup is especially useful if you frequently generate code with STM32CubeMX and want to keep its style consistent.

Using clang-format in Keil: One-Key Formatting for STM32 Projects
https://blog.hanzogenji.cn/posts/tutorials/keil-format-code/
Author
Hanzo Huang
Published at
2025-04-15