969 words
5 minutes
Configuring VSCode and Clangd for STM32 Development

Introduction#

Traditional STM32 development typically relies on IDEs like MDK-ARM or IAR. While capable, they lag behind modern editors in code intelligence, ergonomics, and extensibility. Combining VSCode with Clangd brings fast, accurate code analysis and completion to STM32 development, along with access to VSCode’s rich ecosystem of extensions and AI coding assistants.

NOTE

Updated 2025-10-21

This article was originally written during v1.0 of the STM32 VS Code Extension.

As of v3.6.4, setup is much simpler: after installing the STM32 VS Code Extension, it automatically prompts you to install the required toolchain. Simply generate a CMake project from STM32CubeMX and open it—no manual toolchain wiring needed.

You can largely skip the Setup Steps section (though you still need STM32CubeMX to generate projects), and jump straight to Enhancements for formatting, linting, and CMake tweaks.

If you don’t want the STM32 extension’s bundled plugins cluttering your everyday VSCode setup, consider using VSCode Profiles.

Setup Steps#

1. Install Base Tools#

Download and install the required tools:

Make sure LLVM, CMake, arm-none-eabi-gcc, and Ninja are in your system PATH. Verify them in a terminal with clangd --version, cmake --version, arm-none-eabi-gcc --version, and ninja --version.

2. Install VSCode Extensions#

TIP

The Clangd extension conflicts with Microsoft’s C/C++ extension—disable the C/C++ extension so Clangd can work properly.

Install these extensions from the VSCode Marketplace:

3. Configure the STM32 Toolchain Path#

  1. Press Ctrl + Shift + P in VSCode to open the Command Palette.
  2. Run STM32 VS Code Extension: Configure Cube CLT Path.
  3. Select your STM32CubeCLT installation directory (VSCode usually auto-detects it).

4. Generate and Import a Project#

  1. Create a new project in STM32CubeMX and choose CMake as the toolchain/project type when generating code.
  2. Open the generated folder in VSCode.
  3. Click the STM32 VS Code Extension icon in the Activity Bar and select Import CMake Project.
  4. Select the root directory of the generated STM32CubeMX project.

5. Configure Clangd#

  1. Press Ctrl + Shift + P and run Preferences: Open Workspace Settings (JSON).
  2. Add the following to settings.json:
{
"clangd.arguments": [
"--query-driver=C:/ST/STM32CubeCLT_1.17.0/GNU-tools-for-STM32/bin/arm-none-eabi-*", // Update to your arm-none-eabi-gcc path
"--compile-commands-dir=${workspaceFolder}/build/Debug" // Update to your build directory
],
}

6. Finish Setup#

  1. Press Ctrl + Shift + P and run Developer: Reload Window or clangd: Restart language server.
  2. Wait for Clangd to index the project.

Once complete, code completion and jump-to-definition should work cleanly with no false red squiggles, and you can press F5 to debug directly over ST-Link.

image

Enhancements#

Optional configurations to further improve your workflow:

Code Formatting#

Add a .clang-format file in the project root to customize code formatting rules:

.clang-format (Click to expand)
# Generated by CLion for STL
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: DontAlign
AlignConsecutiveAssignments: Consecutive
AlignConsecutiveMacros: Consecutive
AlignEscapedNewlines: Left
AlignOperands: AlignAfterOperator
AlignTrailingComments:
Kind: Never
AllowShortFunctionsOnASingleLine: Empty
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeBinaryOperators: NonAssignment
ColumnLimit: 120
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<yvals(_core)?\.h>$'
Priority: 1
- Regex: '^<(Windows|userenv)\.h>$'
Priority: 3
SortPriority: 3
- Regex: '^<WinIoCtl\.h>$'
Priority: 3
SortPriority: 4
- Regex: '^<__.*\.hpp>$'
Priority: 2
- Regex: '\.hpp[>"]$'
Priority: 5
- Regex: ".*"
Priority: 2
IndentCaseBlocks: true
IndentWidth: 4
IndentWrappedFunctionNames: true
InsertBraces: true
InsertNewlineAtEOF: true
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
PointerAlignment: Left
RemoveSemicolon: true
SpaceAfterCStyleCast: true
SpaceBeforeParens: Custom
SpaceBeforeParensOptions:
AfterRequiresInClause: true
StatementMacros:
- _EXTERN_CXX_WORKAROUND
- _END_EXTERN_CXX_WORKAROUND
- _STD_BEGIN
- _STD_END
- _STDEXT_BEGIN
- _STDEXT_END
- _FMT_P2286_BEGIN
- _FMT_P2286_END
- _EXTERN_C_UNLESS_PURE
- _END_EXTERN_C_UNLESS_PURE

Static Analysis#

Add a .clang-tidy file in the project root to enable deeper static code analysis:

.clang-tidy (Click to expand)
# Generated from CLion Inspection settings
---
Checks: '-*,
bugprone-argument-comment,
bugprone-assert-side-effect,
bugprone-bad-signal-to-kill-thread,
bugprone-branch-clone,
bugprone-copy-constructor-init,
bugprone-dangling-handle,
bugprone-dynamic-static-initializers,
bugprone-fold-init-type,
bugprone-forward-declaration-namespace,
bugprone-forwarding-reference-overload,
bugprone-inaccurate-erase,
bugprone-incorrect-roundings,
bugprone-integer-division,
bugprone-lambda-function-name,
bugprone-macro-parentheses,
bugprone-macro-repeated-side-effects,
bugprone-misplaced-operator-in-strlen-in-alloc,
bugprone-misplaced-pointer-arithmetic-in-alloc,
bugprone-misplaced-widening-cast,
bugprone-move-forwarding-reference,
bugprone-multiple-statement-macro,
bugprone-no-escape,
bugprone-parent-virtual-call,
bugprone-posix-return,
bugprone-reserved-identifier,
bugprone-sizeof-container,
bugprone-sizeof-expression,
bugprone-spuriously-wake-up-functions,
bugprone-string-constructor,
bugprone-string-integer-assignment,
bugprone-string-literal-with-embedded-nul,
bugprone-suspicious-enum-usage,
bugprone-suspicious-include,
bugprone-suspicious-memset-usage,
bugprone-suspicious-missing-comma,
bugprone-suspicious-semicolon,
bugprone-suspicious-string-compare,
bugprone-suspicious-memory-comparison,
bugprone-suspicious-realloc-usage,
bugprone-swapped-arguments,
bugprone-terminating-continue,
bugprone-throw-keyword-missing,
bugprone-too-small-loop-variable,
bugprone-undefined-memory-manipulation,
bugprone-undelegated-constructor,
bugprone-unhandled-self-assignment,
bugprone-unused-raii,
bugprone-unused-return-value,
bugprone-use-after-move,
bugprone-virtual-near-miss,
cert-dcl21-cpp,
cert-dcl58-cpp,
cert-err34-c,
cert-err52-cpp,
cert-err60-cpp,
cert-flp30-c,
cert-msc50-cpp,
cert-msc51-cpp,
cert-str34-c,
cppcoreguidelines-interfaces-global-init,
cppcoreguidelines-narrowing-conversions,
cppcoreguidelines-pro-type-member-init,
cppcoreguidelines-pro-type-static-cast-downcast,
cppcoreguidelines-slicing,
google-default-arguments,
google-explicit-constructor,
google-runtime-operator,
hicpp-exception-baseclass,
hicpp-multiway-paths-covered,
misc-misplaced-const,
misc-new-delete-overloads,
misc-no-recursion,
misc-non-copyable-objects,
misc-throw-by-value-catch-by-reference,
misc-unconventional-assign-operator,
misc-uniqueptr-reset-release,
modernize-avoid-bind,
modernize-concat-nested-namespaces,
modernize-deprecated-headers,
modernize-deprecated-ios-base-aliases,
modernize-loop-convert,
modernize-make-shared,
modernize-make-unique,
modernize-pass-by-value,
modernize-raw-string-literal,
modernize-redundant-void-arg,
modernize-replace-auto-ptr,
modernize-replace-disallow-copy-and-assign-macro,
modernize-replace-random-shuffle,
modernize-return-braced-init-list,
modernize-shrink-to-fit,
modernize-unary-static-assert,
modernize-use-auto,
modernize-use-bool-literals,
modernize-use-emplace,
modernize-use-equals-default,
modernize-use-equals-delete,
modernize-use-nodiscard,
modernize-use-noexcept,
modernize-use-nullptr,
modernize-use-override,
modernize-use-transparent-functors,
modernize-use-uncaught-exceptions,
mpi-buffer-deref,
mpi-type-mismatch,
openmp-use-default-none,
performance-faster-string-find,
performance-for-range-copy,
performance-implicit-conversion-in-loop,
performance-inefficient-algorithm,
performance-inefficient-string-concatenation,
performance-inefficient-vector-operation,
performance-move-const-arg,
performance-move-constructor-init,
performance-no-automatic-move,
performance-noexcept-move-constructor,
performance-trivially-destructible,
performance-type-promotion-in-math-fn,
performance-unnecessary-copy-initialization,
performance-unnecessary-value-param,
portability-simd-intrinsics,
readability-avoid-const-params-in-decls,
readability-const-return-type,
readability-container-size-empty,
readability-convert-member-functions-to-static,
readability-delete-null-pointer,
readability-deleted-default,
readability-inconsistent-declaration-parameter-name,
readability-make-member-function-const,
readability-misleading-indentation,
readability-misplaced-array-index,
readability-non-const-parameter,
readability-redundant-control-flow,
readability-redundant-declaration,
readability-redundant-function-ptr-dereference,
readability-redundant-smartptr-get,
readability-redundant-string-cstr,
readability-redundant-string-init,
readability-simplify-subscript-expr,
readability-static-accessed-through-instance,
readability-static-definition-in-anonymous-namespace,
readability-string-compare,
readability-uniqueptr-delete-release,
readability-use-anyofallof'

Enabling C++ Support#

To use C++ in your project, update CMakeLists.txt:

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS ON)
enable_language(C ASM CXX) # Replace the existing enable_language line

This enables C++ support and sets the standard to C++20.

Generating HEX and BIN Files#

To automatically generate .hex and .bin firmware images after each build, add the following to CMakeLists.txt:

# Add custom command to generate binary and hex files
add_custom_command(TARGET ${CMAKE_PROJECT_NAME} POST_BUILD
COMMAND ${CMAKE_OBJCOPY} -O binary ${CMAKE_PROJECT_NAME}.elf ${CMAKE_PROJECT_NAME}.bin
COMMAND ${CMAKE_OBJCOPY} -O ihex ${CMAKE_PROJECT_NAME}.elf ${CMAKE_PROJECT_NAME}.hex
)

Adding Custom Source Files#

To keep your own code organized in a dedicated directory (e.g., Core/App), add it in CMakeLists.txt:

# Add sources path
file(GLOB_RECURSE SOURCES
${CMAKE_SOURCE_DIR}/Core/App/*.*
)
# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
# Add user sources here
${SOURCES}
)

Adding Custom Include Paths#

Similarly, register custom header directories:

# Add include paths
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
# Add user defined include paths
${CMAKE_SOURCE_DIR}/Core/App
)

Tuning Compiler and Linker Flags#

You can adjust flags in gcc-arm-none-eabi.cmake as needed:

# Customize C++ flags (e.g. disable RTTI and exceptions)
set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -fno-rtti -fno-exceptions -fno-threadsafe-statics")
set(CMAKE_C_LINK_FLAGS "${TARGET_FLAGS}")
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} -T \"${CMAKE_SOURCE_DIR}/STM32F411XX_FLASH.ld\"")
# Remove `--specs=nano.specs` if you need the full standard library
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} --specs=nano.specs")
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} -Wl,-Map=${CMAKE_PROJECT_NAME}.map -Wl,--gc-sections")
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} -Wl,--start-group -lc -lm -Wl,--end-group")
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} -Wl,--print-memory-usage")
# Enable float formatting in printf (unnecessary when using the full standard library)
set(CMAKE_C_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} -u _printf_float")
set(CMAKE_CXX_LINK_FLAGS "${CMAKE_C_LINK_FLAGS} -Wl,--start-group -lstdc++ -lsupc++ -Wl,--end-group")

Troubleshooting#

IntelliSense Not Working#

  1. Confirm the Clangd extension is installed and Microsoft’s C/C++ extension is disabled.
  2. Make sure compile_commands.json has been generated in the build directory.
  3. Verify the compiler path in settings.json (--query-driver).
  4. Clangd may parse .h files as C headers even when they use C++ features—rename C++ headers to .hpp to avoid parse errors.
Configuring VSCode and Clangd for STM32 Development
https://blog.chauyin.com/en/posts/vscode-configure-clangd-develop-stm32/
Author
Chauyin
Published at
2025-03-24