Automotive Embedded C/C++/CAPL Best Practices
Comprehensive coding guidelines for automotive embedded software development in C, C++, and CAPL. Contains 180+ rules across 23 categories, prioritized by safety impact and industry compliance requirements (MISRA C:2012, MISRA C++:2023, AUTOSAR C++14 Classic & Adaptive, ISO 26262, ISO 21434). Covers full automotive communication stack (CAN/LIN/Ethernet/IP/TSN), cybersecurity, diagnostics, CAPL simulation/testing/fault injection, AUTOSAR BSW modules, boot/NVM/power management, compiler toolchains, static analysis tools, and CI/CD integration.
When to Apply
Reference these guidelines when:
- Writing new embedded C/C++ modules for automotive ECUs
- Implementing or reviewing CAN/LIN/Ethernet communication stacks
- Writing CAPL scripts for CANoe/CANalyzer simulation and testing
- Refactoring code for MISRA C/C++ or AUTOSAR C++14 compliance
- Designing safety-critical software (ASIL A-D per ISO 26262)
- Implementing RTOS task management and inter-task communication
- Reviewing code for memory safety, timing, and determinism
- Working with diagnostic protocols (UDS, OBD-II, DoIP)
- Implementing Automotive Ethernet (TCP, UDP, SOME/IP, DoIP, VLAN)
- Addressing cybersecurity requirements (ISO 21434, secure boot, TLS)
- Integrating with calibration/diagnostic tools (A2L, ODX, XCP)
- Optimizing for resource-constrained microcontrollers (RAM, Flash, CPU)
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Memory Safety & Management | CRITICAL | memory- |
| 2 | MISRA C/C++ Compliance | CRITICAL | misra- |
| 3 | AUTOSAR C++14 Guidelines (Classic & Adaptive) | CRITICAL | autosar- |
| 4 | Safety & Functional Safety (ISO 26262) | HIGH | safety- |
| 5 | Real-Time & Timing Constraints | HIGH | realtime- |
| 6 | Communication Protocols (CAN/LIN/Ethernet/IP/UDS) | HIGH | comm- |
| 7 | Concurrency & RTOS Patterns | MEDIUM-HIGH | rtos- |
| 8 | CAPL Scripting — CANoe | MEDIUM-HIGH | capl-canoe- |
| 9 | CAPL Scripting — vTESTstudio | MEDIUM-HIGH | capl-vtest- |
| 10 | Code Organization & Architecture | MEDIUM | arch- |
| 11 | Performance Optimization | MEDIUM | perf- |
| 12 | Build, Compilation & Static Analysis | MEDIUM | build- |
| 13 | Security & Cybersecurity (ISO 21434) | HIGH | security- |
| 14 | Testing & Verification | MEDIUM | test- |
| 15 | Tool Integration (A2L/ODX/FIBEX) | MEDIUM | integration- |
Quick Reference
1. Memory Safety & Management (CRITICAL)
memory-stack-over-heap- Prefer stack allocation over heap in embedded contextmemory-static-allocation- Use static allocation for deterministic memory usagememory-buffer-bounds- Always validate buffer boundaries before accessmemory-pool-pattern- Use memory pool patterns for dynamic-like allocationmemory-no-malloc-in-rt- Never use malloc/free in real-time critical pathsmemory-raii-cpp- Use RAII for resource management in C++ embedded codememory-volatile-correctness- Use volatile correctly for hardware registers and shared datamemory-alignment- Ensure proper data structure alignment for target architecturememory-zero-init- Always initialize variables, especially in safety-critical code
2. MISRA C/C++ Compliance (CRITICAL)
misra-no-implicit-conversions- Avoid implicit type conversionsmisra-single-exit-point- Prefer single function exit point for critical functionsmisra-no-dynamic-memory- Avoid dynamic memory allocation (Rule 21.3)misra-no-recursion- Avoid recursion in embedded context (Rule 17.2)misra-switch-default- Always include default case in switch statementsmisra-no-goto- Avoid goto except for error cleanup patterns in Cmisra-boolean-expressions- Use explicit boolean comparisonsmisra-pointer-arithmetic- Restrict pointer arithmetic to array indexingmisra-side-effects- Avoid side effects in conditional expressions
3. AUTOSAR C++14 Guidelines (CRITICAL)
autosar-smart-pointers- Use smart pointers instead of raw pointers for ownershipautosar-no-exceptions-rt- Avoid exceptions in real-time contexts, use Result typesautosar-const-correctness- Apply const-correctness throughout interfacesautosar-override-final- Always use override/final for virtual function overridesautosar-enum-class- Use enum class instead of plain enumautosar-no-unions- Avoid unions, use std::variant when neededautosar-braces-init- Prefer braced initialization to prevent narrowingautosar-nodiscard- Use [[nodiscard]] for functions with important return values
4. Safety & Functional Safety - ISO 26262 (HIGH)
safety-defensive-programming- Apply defensive programming at module boundariessafety-error-detection- Implement error detection and plausibility checkssafety-redundant-checks- Use redundant checks for critical control pathssafety-watchdog-pattern- Implement watchdog monitoring patternssafety-state-machine-integrity- Protect state machine transitions from corruptionsafety-crc-validation- Validate data integrity with CRC for critical datasafety-safe-state- Always define and reach safe state on failuresafety-asil-decomposition- Follow ASIL decomposition patterns correctly
5. Real-Time & Timing Constraints (HIGH)
realtime-deterministic-execution- Ensure deterministic execution time in cyclic tasksrealtime-wcet-awareness- Design with WCET (Worst-Case Execution Time) in mindrealtime-no-blocking-isr- Never block in interrupt service routinesrealtime-priority-inversion- Prevent priority inversion with proper lockingrealtime-cyclic-scheduling- Follow cyclic scheduling patterns correctlyrealtime-interrupt-latency- Minimize interrupt latency and ISR execution timerealtime-deadline-monitoring- Implement deadline monitoring for critical tasks
6. Communication Protocols (HIGH)
CAN / LIN Bus:
comm-can-message-layout- Follow proper CAN/CAN FD message layout and DBC conventionscomm-can-error-handling- Handle CAN bus-off recovery and error framescomm-can-fd-handling- Handle CAN FD extended data length and bit rate switchingcomm-lin-schedule-table- Implement LIN schedule tables and response handlingcomm-signal-timeout- Implement signal timeout monitoring with default valuescomm-network-management- Follow NM (Network Management) state machine correctly
Automotive Ethernet / IP Stack:
comm-tcp-socket-lifecycle- Manage TCP socket lifecycle (connect, keepalive, graceful shutdown)comm-udp-datagram-handling- Handle UDP datagrams for service discovery and streamingcomm-doip-implementation- Implement Diagnostics over IP (ISO 13400) activation and routingcomm-arp-table-management- Manage ARP tables and static ARP entries for deterministic networkscomm-icmp-handling- Handle ICMP for network diagnostics and reachability detectioncomm-vlan-qos-priority- Configure VLAN tagging and QoS priority mapping (IEEE 802.1Q)comm-dhcp-autoip- Implement IP address assignment (DHCP client, AutoIP fallback)comm-someip-serialization- Use correct SOME/IP serialization for service-oriented communicationcomm-someip-sd- Implement SOME/IP Service Discovery (offer, find, subscribe)
Diagnostics & Routing:
comm-uds-service-handler- Implement UDS diagnostic services with proper NRC handlingcomm-gateway-routing- Implement proper message routing in gateway ECUs
7. Concurrency & RTOS Patterns (MEDIUM-HIGH)
rtos-task-design- Design tasks with single responsibility and proper priorityrtos-critical-section- Minimize critical section durationrtos-mutex-pattern- Use mutexes correctly, avoid nested lockingrtos-message-queue- Prefer message queues over shared memory for inter-task communicationrtos-no-priority-inversion- Use priority inheritance or ceiling protocolsrtos-isr-to-task- Defer ISR processing to task context via flags/queuesrtos-stack-sizing- Size task stacks correctly with safety margin
8. CAPL Scripting — CANoe (MEDIUM-HIGH)
capl-canoe-message-handler- Structure message handlers for readability and performancecapl-canoe-timer-pattern- Use timer patterns correctly for cyclic and one-shot operationscapl-canoe-test-structure- Structure test cases with proper setup/teardown/verificationcapl-canoe-signal-access- Access signals via database symbols, not raw byte manipulationcapl-canoe-error-frame-handling- Handle error frames and bus-off conditions in simulationcapl-canoe-environment-variables- Use environment variables for panel interaction correctlycapl-canoe-diagnostic-testing- Implement diagnostic request/response testing patternscapl-canoe-node-simulation- Design node simulation with proper state machinescapl-canoe-multi-channel- Multi-channel bus simulation (CAN+CAN, CAN+LIN, CAN+ETH)capl-canoe-rbs-cyclic- Cyclic Rest Bus Simulation with counter/CRC generationcapl-canoe-rbs-reactive- Reactive RBS with Interaction Layer and state-dependent responsescapl-canoe-gateway-routing- Gateway simulation with signal/PDU/cross-protocol routing
8b. CAPL — Shared Patterns (MEDIUM-HIGH)
capl-signal-manipulation- Reusable signal manipulation library (ramp, sine, noise, step, sequence)
8c. CAPL — Fault Injection (HIGH)
capl-fault-can- CAN/CAN FD fault injection (error frames, bus-off, signal stuck, timing)capl-fault-lin- LIN fault injection (checksum, no-response, header, timing)capl-fault-eth- Ethernet fault injection (link down, packet loss, latency, corruption)
8d. CAPL — External Integration (MEDIUM)
capl-ext-dll-integration- CAPL DLL API, data exchange, thread safety, 32/64-bitcapl-ext-com-python- CANoe COM automation via Pythoncapl-ext-com-csharp- CANoe COM automation via C#capl-ext-ci-cd- CI/CD integration (Jenkins, GitLab CI, headless execution)
9. Code Organization & Architecture (MEDIUM)
arch-hal-abstraction- Use Hardware Abstraction Layer for portabilityarch-module-interface- Design clean module interfaces with information hidingarch-state-machine- Implement state machines with table-driven or state-pattern approacharch-callback-pattern- Use callback patterns for decoupling layersarch-config-separation- Separate configuration from logic (calibration parameters)arch-layered-architecture- Follow layered architecture (MCAL, ECU-AL, BSW, SWC)
10. Performance Optimization (MEDIUM)
perf-loop-optimization- Optimize loop constructs for embedded targetsperf-lookup-table- Use lookup tables instead of runtime computationperf-bitwise-operations- Use bitwise operations for flag and register manipulationperf-cache-friendly- Organize data for CPU cache efficiencyperf-inline-critical- Inline small, critical functionsperf-fixed-point- Use fixed-point arithmetic instead of floating-point when possibleperf-dma-usage- Use DMA for bulk data transfers
11. Build, Compilation & Static Analysis (MEDIUM)
build-warnings-as-errors- Treat all compiler warnings as errorsbuild-static-analysis- Integrate static analysis (PC-lint, Polyspace, Coverity)build-compiler-flags- Use appropriate compiler flags for safety and optimizationbuild-link-time-optimization- Use LTO for cross-module optimizationbuild-reproducible-builds- Ensure reproducible builds for traceability
12. Testing & Verification (MEDIUM)
test-unit-test-pattern- Structure unit tests for embedded C/C++ (Unity, Google Test)test-mock-hardware- Mock hardware dependencies for testabilitytest-boundary-values- Test boundary values and edge cases systematicallytest-coverage-targets- Meet code coverage targets per ASIL leveltest-integration-testing- Design integration tests for inter-module communicationtest-hil-sil-pattern- Structure HIL/SIL test patterns for verification
13. Security & Cybersecurity — ISO 21434 (HIGH)
security-secure-boot- Implement secure boot chain verificationsecurity-secure-communication- Use TLS/DTLS for in-vehicle Ethernet communicationsecurity-key-management- Handle cryptographic keys with proper storage and rotationsecurity-secure-diagnostics- Implement secure UDS authentication (0x29 service)security-input-sanitization- Sanitize all external inputs (CAN, Ethernet, diagnostic)security-secure-update- Implement secure OTA/reflash with signature verificationsecurity-access-control- Enforce access control between security domainssecurity-crypto-usage- Use cryptographic primitives correctly (AES, HMAC, CMAC)
14. MISRA Grouped Topics (CRITICAL)
misra-type-system- Essential type model, implicit conversions, type casting (Rules 10-11)misra-control-flow- Switch, goto, unreachable code, single exit (Rules 15-16)misra-pointer-safety- Pointer arithmetic, null checks, conversions (Rules 18, 11)misra-declarations- Variable scope, linkage, storage class (Rules 8)misra-expressions- Side effects, precedence, boolean, sizeof (Rules 12-14)misra-functions- Prototypes, parameters, return values, recursion ban (Rules 17)misra-preprocessor- Macro safety, include guards, conditional compilation (Rules 20)misra-standard-library- Banned functions, restricted headers (Rules 21-22)misra-initialization- Variable/array/struct initialization (Rules 9)misra-memory-model- Volatile, atomic access, memory barriers (Rules 19)misra-concurrency- Thread safety, shared data access (Amendment 4)misra-deviation-process- Deviation documentation, approval, common patterns
15. AUTOSAR Classic BSW Modules (HIGH)
autosar-classic-ecum- EcuM startup/shutdown, sleep/wakeupautosar-classic-bswm- BswM mode arbitration, action listsautosar-classic-com- COM signal packing, transmission modesautosar-classic-pdu-router- PDU Router routing paths, gatewayautosar-classic-dcm-dem- Dcm/Dem diagnostics, DTC managementautosar-classic-nvm- NvM block configuration, CRC, read/writeautosar-classic-os- AUTOSAR OS tasks, ISRs, resources, alarmsautosar-classic-canif-cantp- CanIf/CanTp callbacks, flow control
16. AUTOSAR Adaptive ara:: APIs (HIGH)
autosar-adaptive-ara-com- ara::com proxy/skeleton, service discoveryautosar-adaptive-ara-core- ara::core Result<T,E>, ErrorCode, Futureautosar-adaptive-ara-exec- ara::exec process lifecycle, function groupsautosar-adaptive-ara-diag- ara::diag diagnostic servicesautosar-adaptive-ara-log- ara::log logging patternsautosar-adaptive-ara-phm- ara::phm health management, supervisionautosar-adaptive-ara-per- ara::per persistency, key-value storage
17. ECU Boot Sequence (HIGH)
boot-baremetal-startup- Bare-metal boot: startup → C runtime → mainboot-autosar-classic-startup- Classic AUTOSAR EcuM/BswM bootboot-autosar-adaptive-startup- Adaptive Execution Manager bootboot-bootloader-reprogramming- UDS flash download sequenceboot-secure-boot-chain- Secure boot with HSM verification
18. NVM Management (HIGH)
nvm-autosar-block-config- AUTOSAR NvM blocks, CRC, redundancynvm-fee-ea-abstraction- Fee/Ea Flash EEPROM Emulationnvm-baremetal-flash- Bare-metal Flash/EEPROM patternsnvm-wear-leveling- Wear leveling strategies for automotive lifetime
19. Power Management (MEDIUM)
power-ecum-sleep-wakeup- EcuM sleep/wakeup state machinepower-partial-networking- Partial networking, selective transceiver wakeuppower-bswm-shutdown- BswM ordered shutdown action listspower-clock-peripheral- Clock gating and peripheral power-downpower-low-power-modes- MCU low-power modes (SLEEP, STANDBY, STOP)
20. Automotive Ethernet Deep-Dive (HIGH)
eth-tsn-time-sync- TSN time synchronization (IEEE 802.1AS / gPTP)eth-tsn-traffic-shaping- TSN traffic shaping (IEEE 802.1Qbv)eth-tsn-stream-filtering- TSN stream filtering (IEEE 802.1Qci)eth-switch-configuration- Automotive Ethernet switch configurationeth-avb-streaming- AVB Audio/Video streaming
21. Compiler & Static Analysis (HIGH)
build-gcc-warnings- GCC warning flags for automotivebuild-clang-analysis- Clang-Tidy and Clang Static Analyzerbuild-greenhills-safety- GreenHills safety-qualified compileranalysis-pclint-config- PC-lint MISRA configurationanalysis-polyspace- Polyspace Bug Finder / Code Proveranalysis-coverity- Coverity embedded checkersanalysis-cppcheck- cppcheck with MISRA addonanalysis-parasoft- Parasoft C/C++testanalysis-ldra- LDRA traceability and coverage
22. vTESTstudio CAPL (MEDIUM-HIGH)
capl-vtest-test-unit- Test unit/group/fixture structurecapl-vtest-data-driven- Data-driven testing with parameterscapl-vtest-xml-module- XML test module integrationcapl-vtest-verdict-reporting- Verdict and reporting patternscapl-vtest-stimulus-response- Stimulus/response timing validation
23. Tool Integration (MEDIUM)
integration-a2l-calibration- Generate and maintain A2L/ASAP2 calibration descriptionsintegration-odx-diagnostic- Structure ODX/PDX diagnostic descriptions correctlyintegration-fibex-network- Maintain FIBEX network description filesintegration-dbc-arxml-sync- Keep DBC/ARXML and code signal definitions synchronizedintegration-xcp-calibration- Implement XCP (Universal Measurement and Calibration Protocol)integration-autosar-arxml- Generate and parse AUTOSAR ARXML configuration correctly
How to Use
Read individual rule files for detailed explanations and code examples:
rules/memory-stack-over-heap.md
rules/misra-no-recursion.md
rules/capl-message-handler.md
Each rule file contains:
- Brief explanation of why it matters in automotive embedded context
- Incorrect code example with explanation
- Correct code example with explanation
- Relevant standard references (MISRA, AUTOSAR, ISO 26262)
- Additional context and impact on safety/performance
Full Compiled Document
For the complete guide with all rules expanded: AGENTS.md