Static Analysis for Embedded Systems: PC-lint, MISRA, and Practical Enforcement
Unit tests verify that your code does what you expect. Static analysis finds what you did not think to test. Off-by-one errors, integer overflow on a 16-bit counter, implicit signed/unsigned conversions that work on x86 but break on a 32-bit ARM — these are exactly the class of bugs that slip past human review and pass a test suite because nobody wrote the edge-case test. Static analysis tools read your source code without executing it and flag patterns that are likely wrong.
For embedded systems, two names dominate: PC-lint Plus (commercial, from Gimpel Software) and MISRA C (a coding standard, not a tool). Together they define the state of the art in safety-critical embedded software analysis. This post explains what each provides, how to enforce MISRA C rules in CI, and which violations actually matter.
What Static Analysis Is and Is Not
Static analysis reads source code, builds an abstract model of program behavior, and reports suspicious patterns. It finds:
- Type safety violations — passing a
uint16_twhere a function expectsuint32_t, losing bits silently - Unreachable code — a
returnbefore theelsebranch that was meant to guard it - Uninitialized variables — local variables read before any assignment on some paths
- Integer overflow — an expression that exceeds its type's range
- Null pointer dereferences — pointers that might be null used without a check
- Implicit conversions —
charcompared toEOF (-1)on an unsigned-char platform
Static analysis does NOT verify correctness of logic, performance, or behavior under specific inputs. It is a complement to testing, not a replacement.
MISRA C: What It Is and Why It Matters
MISRA C (Motor Industry Software Reliability Association) is a coding standard published as a set of rules for C programming in embedded and safety-critical systems. The current versions are MISRA C:2012 (with 2023 amendments) and MISRA C++:2023. There are 143 rules in MISRA C:2012, divided into:
- Mandatory — must never be violated (15 rules)
- Required — must be followed or formally deviated from (107 rules)
- Advisory — recommended (21 rules)
MISRA does not publish a free tool. Compliance with MISRA is enforced by commercial static analyzers: PC-lint Plus, LDRA, Polyspace, Klocwork, and QA-C. Several open-source tools (cppcheck, clang-tidy) implement subsets of MISRA rules.
PC-lint Plus: Core Concepts
PC-lint Plus (formerly PC-lint) analyzes C and C++ code with deep type checking, flow analysis, and MISRA C enforcement. It is available for Windows, Linux, and macOS.
Basic usage:
lint-nt +v -i/path/to/lintfiles co-gcc.lnt project.lnt src/pid.cA PC-lint project file (project.lnt) specifies compiler flags, include paths, and enabled rules:
// project.lnt
-i/usr/arm-none-eabi/include
-i../src
-i../hal/include
// Target: ARM Cortex-M4
+fbu // bit fields are unsigned
-cpu(cortex-m4)
// Enable MISRA C 2012
+e900 // produce MISRA messages
au-misra3.lnt
// Suppress known-false-positives for vendor HAL headers
-e750 // local macro not referenced
-elib(*) // suppress messages for library headersPC-lint output:
src/motor.c 42 Warning 9013 (MISRA C 2012 Rule 15.5)
A function should have a single point of exit at the end.
src/sensor.c 78 Warning 9029 (MISRA C 2012 Rule 10.1)
Impermissible operand to operator '>>': Essential type of the left
operand (signed int) is not unsigned.Which MISRA Rules Matter Most in Practice
MISRA has 143 rules and many of them exist for historical reasons. Experienced teams focus on the rules that catch real bugs:
Rule 10.1–10.8: Essential Type Model
The most practically important rules. MISRA defines an "essential type" model that restricts implicit conversions. Rule 10.4 says "both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category."
This catches bugs like:
/* MISRA violation: mixing signed and unsigned */
int16_t temperature = get_temperature(); /* signed */
uint16_t setpoint = get_setpoint(); /* unsigned */
if (temperature < setpoint) { /* Rule 10.4: operands differ in signedness */
/* BUG: if temperature is -5, and setpoint is 20,
this comparison may be wrong on some platforms because
temperature gets converted to a large unsigned value */
}Fix:
if (temperature < (int16_t)setpoint) { /* explicit cast documents intent */Rule 14.4: Controlling Expression of if/while
The controlling expression shall be essentially Boolean. This prevents if (status) where status is an integer — a common source of bugs when a function returns error codes rather than booleans.
HAL_Status_t result = HAL_UART_Transmit(data, len, timeout);
if (result) { /* MISRA 14.4: not essentially Boolean */
handle_error();
}
/* Compliant: */
if (result != HAL_OK) {
handle_error();
}Rule 17.7: Return Value Not Discarded
Every function that returns a value must have that value used or explicitly cast to void. This catches silently ignored error returns — a leading cause of missed error handling in firmware:
xQueueSend(q, &msg, 0); /* MISRA 17.7: return value ignored */
/* Compliant: */
BaseType_t sent = xQueueSend(q, &msg, 0);
if (sent != pdPASS) {
LOG_ERROR("Queue full, message dropped");
}Rule 13.2: Order of Evaluation
The value of an expression and its persistent side effects shall be the same under any order of evaluation. This catches expressions where behavior depends on compiler implementation:
/* MISRA 13.2: order of evaluation of i++ is implementation-defined */
buf[i] = buf[i++];
/* This might work on GCC ARM but break on another compiler or with -O2 */Rule 15.5: Single Exit Point
Functions should have one return statement. This is advisory and many teams deviate from it for early validation returns — but it is worth flagging because deeply nested return statements hide control flow.
Cppcheck: Free MISRA C Subset
Cppcheck is open-source and implements a subset of MISRA C rules. Not a full MISRA checker, but valuable for CI integration without a PC-lint license:
cppcheck --addon=misra --suppress=misra-c2012-1.1 \
--suppress=misra-c2012-2.3 \
--enable=warning,style,performance \
--error-exitcode=1 \
--inline-suppr \
-I src/ \
src/The misra addon requires a copy of MISRA C:2012 text (which you must purchase). Cppcheck reads it via a JSON description file:
# Generate MISRA compliance report
cppcheck --addon=misra.py --dump src/motor.c 2> misra-report.txt
python3 misra.py --rule-texts=misra_c_2012.txt motor.c.dumpFor teams without a MISRA license, cppcheck still catches real bugs with --enable=all:
cppcheck --enable=all --error-exitcode=1 \
-I hal/include -I src/ \
--suppress=missingIncludeSystem \
src/clang-tidy for Embedded
clang-tidy runs on the compilation database and provides several checks relevant to embedded:
# .clang-tidy
Checks: >
bugprone-*,
cert-*,
clang-analyzer-*,
cppcoreguidelines-avoid-non-const-global-variables,
misc-misplaced-const,
readability-non-const-parameter,
-bugprone-easily-swappable-parameters
WarningsAsErrors: 'bugprone-*,cert-*'Generate a compilation database with CMake:
cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -B build
clang-tidy -p build src/**/*.cOr with Bear for non-CMake builds:
bear -- make all
clang-tidy -p compile_commands.json src/motor.cSuppressing False Positives
Every static analyzer produces false positives. The right strategy is to suppress them inline with a comment that explains why, so future readers understand the intent:
/* PRQA S 0306 1 -- Required for hardware register access via memory-mapped pointer */
volatile uint32_t *reg = (volatile uint32_t *)0x40020000UL;
/* lint -e9078 [MISRA C 2012 Rule 11.4] Required: direct hardware register access */
volatile GPIOA_TypeDef *gpio = (volatile GPIOA_TypeDef *)GPIOA_BASE;Blanket suppressions with -e* or // NOLINT for entire files hide real issues. Suppress only the specific rule, only on the specific line, with an explanation.
CI Integration
Add static analysis to your CI pipeline as a required gate:
# .github/workflows/static-analysis.yml
name: Static Analysis
on: [push, pull_request]
jobs:
cppcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install cppcheck
run: sudo apt-get install -y cppcheck
- name: Run cppcheck
run: |
cppcheck \
--enable=warning,style,performance,portability \
--error-exitcode=1 \
--suppress=missingIncludeSystem \
--inline-suppr \
-I src/ \
--xml --xml-version=2 \
src/ 2> cppcheck-results.xml
- name: Upload results
uses: actions/upload-artifact@v4
if: always()
with:
name: cppcheck-report
path: cppcheck-results.xml
clang-tidy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install clang-tidy
run: sudo apt-get install -y clang-tidy bear gcc-arm-none-eabi
- name: Generate compile commands
run: bear -- make -C firmware all CROSS_COMPILE=arm-none-eabi-
- name: Run clang-tidy
run: |
clang-tidy \
-p firmware/compile_commands.json \
--warnings-as-errors='bugprone-*' \
firmware/src/*.cPrioritizing What to Fix
A typical codebase will produce hundreds of static analysis warnings on first run. Do not try to fix them all at once. Triage by risk:
Fix immediately:
- Uninitialized variables read on any path
- Integer overflow in safety-critical calculations (PWM duty cycle, ADC scaling)
- Null pointer dereferences without prior null checks
- Buffer size mismatches
Fix this sprint:
- Signed/unsigned comparison warnings in arithmetic
- Ignored return values from HAL functions (HAL_UART_Transmit, etc.)
- Implicit narrowing conversions in function calls
Track and defer:
- Style-only warnings (naming conventions, single exit point)
- Advisory MISRA rules in non-safety-critical modules
- Warnings in vendor-supplied HAL code you cannot modify
Set a policy: the warning count in new code must be zero. Fix legacy warnings incrementally. Never allow the count to grow.
Summary
Static analysis for embedded firmware is not optional in safety-critical products and is increasingly expected in any professional firmware codebase. PC-lint Plus provides the most thorough MISRA C enforcement for teams with commercial tool budgets. Cppcheck and clang-tidy provide significant value for free and integrate easily into any CI pipeline. The key to making static analysis useful rather than annoying is triage: suppress false positives with documented justifications, fix high-risk warnings immediately, and treat the analyzer as a code reviewer that never misses an edge case. A codebase where static analysis runs clean is a codebase where integer overflow bugs and missing null checks do not ship to hardware.