0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Use Inline Functions in Embedded C for Efficient Code

In Embedded C, use the inline keyword before a function definition to suggest the compiler replace function calls with the function code itself, reducing call overhead. This is useful for small, frequently called functions to improve speed and reduce stack usage.
📐

Syntax

The inline keyword is placed before the function return type to suggest inlining. The function can be defined in a header or source file. Example parts:

  • inline: Suggests inlining to the compiler.
  • return_type: The data type the function returns.
  • function_name(parameters): The function signature.
  • Function body: The code to execute.
c
inline int add(int a, int b) {
    return a + b;
}
💻

Example

This example shows an inline function multiply used inside main. The compiler replaces calls to multiply with its code to avoid function call overhead.

c
#include <stdio.h>

inline int multiply(int x, int y) {
    return x * y;
}

int main() {
    int result = multiply(5, 6);
    printf("Result: %d\n", result);
    return 0;
}
Output
Result: 30
⚠️

Common Pitfalls

Common mistakes when using inline functions in Embedded C include:

  • Assuming inline forces inlining; it is only a suggestion to the compiler.
  • Defining inline functions in source files (.c) without static can cause linker errors.
  • Using large functions as inline can increase code size, hurting memory usage.
  • Not placing inline functions in headers when used across multiple files.
c
/* Wrong: Inline function in .c file without static */
inline int add(int a, int b) {
    return a + b;
}

/* Right: Use static inline in .c or inline in header */
static inline int add(int a, int b) {
    return a + b;
}
📊

Quick Reference

KeywordDescription
inlineSuggests compiler to replace function calls with code
static inlineDefines inline function with internal linkage to avoid linker errors
Use in headersPlace inline functions in headers for multi-file use
Small functionsBest for small, frequently called functions
Compiler dependentInlining is a compiler optimization, not guaranteed

Key Takeaways

Use the inline keyword before a function to suggest inlining to the compiler.
Place inline functions in headers or use static inline in source files to avoid linker issues.
Inline functions are best for small, frequently called code to improve speed.
Inlining is a suggestion; the compiler decides whether to inline or not.
Avoid large inline functions to prevent code size increase in embedded systems.