What are typedef Portability and Pitfalls- Online Embedded C Programming Classes

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free Embedded C Course · Structure and Union

typedef Portability and Pitfalls

Use typedef to keep firmware portable across targets, and learn the three pitfalls that trip up beginners: no new type, no unsigned, and the const pointer surprise.

Firmware moves between chips more often than most programmers expect. A driver written for a 32-bit ARM Cortex-M part gets reused on a small 8-bit or 16-bit microcontroller, and then on a Linux host for unit testing. The thing that breaks first is the size of the basic types. Using typedef in embedded C is how experienced engineers keep that breakage in a single line. This lecture of the free embedded C course shows the portability argument with real compiled output, then covers the pitfalls that catch learners: typedef names do not accept unsigned, a typedef is not a new type, and const behaves strangely in front of a pointer alias.

typedef in embedded Cfree embedded C coursefree C programming courseembedded C programmingfixed-width typesportable firmware

What You Will Learn

  • Why basic C types change size between targets and how typedef in embedded C hides that
  • How to combine typedef with stdint.h fixed-width types
  • What a typedef is not: it creates no new type and no type safety
  • Why unsigned and long cannot be added to a typedef name
  • The const and typedef pointer trap, with the real compiler message
  • A checklist of typedef habits used in professional firmware

Prerequisites

You should know basic typedef syntax, structures and pointers. If the word typedef is new to you, read the earlier lectures of this chapter first. Any GCC installation on Linux, macOS or Windows is enough to repeat the examples in this free C programming course.

Why Type Sizes Differ Between Targets

The C language does not promise how many bytes an int has. It only promises minimum ranges. Older textbooks often assume a two-byte int, because that was true on the machines of the time. On a modern 32-bit microcontroller an int is four bytes, and on a small 8-bit part it may still be two. The size of long varies as well: it is typically four bytes on a 32-bit embedded target and eight bytes on a 64-bit Linux PC.

One typedef line, different targets underneath
Small 8-bit or 16-bit MCU
int is often 2 bytes
32-bit Cortex-M
int 4 bytes, long 4 bytes
64-bit Linux PC
int 4 bytes, long 8 bytes
Your code writes
reg_t ctrl;
The typedef maps it to
uint32_t on every target
TypeSize is guaranteed?Typical embedded surprise
charAt least 8 bits, one byte by definitionSignedness is implementation defined
intAt least 16 bitsDiffers between 16-bit and 32-bit parts
longAt least 32 bits4 bytes on many MCUs, 8 bytes on 64-bit Linux
uint32_tExactly 32 bits when the target provides itSafe choice for register images

Because the guarantees are weak, portable code never writes a register layout with bare int. It names the width it wants.

Using Typedef in Embedded C for Portability

The idea is simple. Put the choice of underlying type in one typedef, and use only that typedef everywhere else. When a new target needs a different choice, you edit one line.

#include <stdio.h>
#include <stdint.h>
#include <limits.h>

/* One place to change when the target changes. */
typedef uint32_t reg_t;         /* a 32-bit hardware register   */
typedef uint8_t  byte_t;        /* raw byte                     */
typedef int      counter_t;     /* plain loop/event counter     */

typedef struct tag_both {
    int  i;
    char c;
} tag_both;                     /* tag and typedef name may match */

int main(void)
{
    reg_t ctrl = 0xA5A50001u;
    byte_t low = (byte_t)(ctrl & 0xFFu);
    counter_t n = 0;

    n += 2;
    printf("sizeof(reg_t)=%zu sizeof(byte_t)=%zu sizeof(counter_t)=%zu\n",
           sizeof(reg_t), sizeof(byte_t), sizeof(counter_t));
    printf("ctrl=0x%08X low=0x%02X n=%d\n", (unsigned)ctrl, low, n);
    printf("INT_MAX=%d  sizeof(long)=%zu\n", INT_MAX, sizeof(long));

    struct tag_both v1 = { 1, 'a' };
    tag_both        v2 = { 2, 'b' };
    printf("%d %c %d %c\n", v1.i, v1.c, v2.i, v2.c);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra -o typedef_port typedef_port.c
$ ./typedef_port
sizeof(reg_t)=4 sizeof(byte_t)=1 sizeof(counter_t)=4
ctrl=0xA5A50001 low=0x01 n=2
INT_MAX=2147483647  sizeof(long)=8
1 a 2 b

The output above came from a 64-bit Linux PC, which is why sizeof(long) prints 8. On a 32-bit Cortex-M target the same line would print 4, but reg_t would still be exactly four bytes, because it is built on uint32_t and not on long.

The last two lines of the program show a second property: a tag and a typedef name may be identical. struct tag_both and tag_both name the same type, so both declarations work.

Name the Meaning, Not Just the Width

Good firmware typedefs describe the job. adc_raw_t tells the reader that a value is an unconverted converter reading. tick_t says a number counts scheduler ticks. If the tick counter later grows from 32 to 64 bits, you change one line. This is also the practical meaning behind the old textbook advice that typedef makes programs more portable: the typedef becomes the only place that knows the real width.

What a Typedef Is Not

A typedef is an alias. The compiler treats the alias and the original as one type. That has an uncomfortable consequence for typedef in embedded C: you gain readability but no safety.

typedef uint32_t freq_hz_t;
typedef uint32_t timeout_ms_t;

freq_hz_t f = 16000000u;
timeout_ms_t t = f;      /* compiles without a warning */

The two names above are different words for the same uint32_t. If you want the compiler to reject mixing them, give each its own one-member struct, for example typedef struct { uint32_t v; } freq_hz_t;. That costs nothing at run time with a normal optimiser and catches unit mix-ups at compile time.

Pitfall: You Cannot Add unsigned to a Typedef Name

The keywords unsigned, signed, short and long combine only with built-in type keywords. A typedef name is not a built-in keyword, so the combination is a syntax error. This is a clear difference from a macro, where the text substitution would make it work.

#include <stdio.h>

typedef short int small_t;

int main(void)
{
    /* typedef names are not macros: you cannot bolt 'unsigned' on the front */
    unsigned small_t v = 3;
    printf("%u\n", v);
    return 0;
}
$ gcc -std=c11 -Wall -Wextra typedef_bad2.c
typedef_bad2.c:8:22: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'v'
typedef_bad2.c:8:22: error: 'v' undeclared (first use in this function)

How to Fix It

Define a second typedef that already contains the sign: typedef unsigned short ushort_t;. In new code, prefer uint16_t from stdint.h, which states signedness and width together.

Pitfall: const and a Typedef’d Pointer

This one costs even experienced programmers an afternoon. When a typedef hides a pointer, const no longer attaches to the thing you think it does.

#include <stdio.h>

typedef char *str_t;

int main(void)
{
    char a[] = "abc", b[] = "xyz";
    const str_t p = a;      /* reads like "pointer to const char" - it is not */

    p[0] = 'Z';             /* allowed: the characters are NOT const */
    printf("%s\n", a);
    p = b;                  /* rejected: the pointer itself is const */
    return 0;
}
$ gcc -std=c11 -Wall -Wextra constptr.c
constptr.c:12:7: error: assignment of read-only variable 'p'

The line p[0] = 'Z'; compiled, so the characters are not read-only. Only the assignment to p itself was rejected. Because str_t is char *, the declaration const str_t p means char *const p, a constant pointer to modifiable data. If you wanted read-only characters, you need const char * written out, or a second typedef for it. This is the main reason many style guides say: do not hide pointers behind typedef names.

Common Mistakes with Typedef in Embedded C

MistakeWhy it happensBetter habit
Using plain int for a 32-bit register imageAssumes int is always 32 bitstypedef uint32_t reg_t;
Writing unsigned before a typedef nameTreats the alias like a macroCreate a separate unsigned typedef
Expecting separate typedefs to catch unit errorsAlias means same typeWrap the value in a struct when safety matters
Hiding pointers and then adding constConst binds to the pointerKeep const char * visible
Scattering long and short through the codeHard to port laterName each width once in a header

Best Practices for Typedef in Embedded C

  • Keep all project typedefs in one header such as types.h, so a port touches one file.
  • Build typedefs on stdint.h types, not on int, short or long.
  • Name the meaning (tick_t, adc_raw_t), not only the width.
  • Use a struct wrapper when two values must never be mixed.
  • Do not typedef away a pointer unless the type is a deliberate opaque handle.
  • Check sizeof with a compile-time assertion for any type that must match hardware, for example _Static_assert(sizeof(reg_t) == 4, "reg_t must be 32 bit");.

Performance and security considerations. Typedefs cost nothing at run time. The safety value comes from catching size mismatches early: a register image that silently becomes eight bytes on one target can corrupt neighbouring memory, so a static assertion at build time is cheap insurance.

Real-World Use Cases

  • A vendor peripheral library defines its own integer typedefs once, so the same driver compiles for several chip families.
  • A protocol parser keeps field types such as opcode_t and handle_t in a header so they can grow when the specification changes.
  • Unit tests compile firmware modules on a Linux host. The test build maps the typedef to the host’s types, while the target build maps it to hardware types.

Summary and Key Takeaways

  • Basic C types change size between targets; typedef in embedded C pins the choice in one place.
  • Build typedefs on fixed-width types from stdint.h.
  • A typedef is an alias, not a new type, so it gives no type safety by itself.
  • unsigned, long and short cannot be added to a typedef name.
  • const in front of a pointer typedef makes the pointer constant, not the data.

Conclusion

Typedef in embedded C is less about saving keystrokes and more about controlling change. One header decides what a register, a tick or a raw sample really is on each target, and everything else uses the name. Remember the three traps: the alias is the same type, specifiers cannot be bolted on, and const binds to hidden pointers. With those in mind your drivers stay portable as the hardware underneath them changes. Next in this free C programming course we practise structure copying, comparison and passing, with the compiler errors printed in full.

typedef in embedded C FAQ

Why is typedef in embedded C used so much for register types?

Hardware registers have a fixed width, but the size of plain int and long changes between compilers and CPUs. A typedef such as reg_t built on uint32_t pins the width in one line and keeps every register access consistent.

Does a typedef create a new, incompatible type?

No. It creates another name for the same type. Two typedef names built on uint32_t can be mixed freely, and the compiler will not warn you. If you need real separation, wrap the value in a one-member struct.

Why does unsigned my_type not compile when my_type is a typedef?

Specifiers such as unsigned, long and short modify built-in type keywords. They cannot be attached to a typedef name. Define a second typedef, for example typedef unsigned short ushort_t;.

What does const do in front of a typedef’d pointer?

It makes the pointer variable itself constant, not the data it points to. With typedef char *str_t;, the declaration const str_t p means char *const p. This surprises many programmers.

Should I use my own typedefs or just uint8_t, uint16_t and uint32_t?

Use the fixed-width types from stdint.h for anything with a defined width, and add your own typedef on top when the name carries meaning, such as reg_t, adc_raw_t or tick_t.

Is typedef better than #define for types?

Yes. A typedef obeys scope and handles pointer types correctly, while a macro is plain text substitution. The previous lecture on typedef basics showed the pointer declaration trap.

Does using typedefs make my firmware slower or larger?

No. Typedefs vanish during compilation. The generated code depends only on the underlying type.

Continue the Free C Programming Course

Next: copying and comparing structures, including the padding trap that makes memcmp lie.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →