C++ usage in embedded systems

后端 未结 17 1519
南旧
南旧 2021-01-30 22:45

What features of C++ should be avoided in embedded systems?

Please classify the answer by reason such as:

  • memory usage
  • code size
  • speed<
17条回答
  •  长发绾君心
    2021-01-30 23:16

    If you're using an ARM7TDMI, avoid unaligned memory accesses at all costs.

    The basic ARM7TDMI core does not have alignment checking, and will return rotated data when you do an unaligned read. Some implementations have additional circuitry for raising an ABORT exception, but if you don't have one of those implementations, finding bugs due to unaligned accesses is very painful.

    Example:

    const char x[] = "ARM7TDMI";
    unsigned int y = *reinterpret_cast(&x[3]);
    printf("%c%c%c%c\n", y, y>>8, y>>16, y>>24);
    
    • On an x86/x64 CPU, this prints "7TDM".
    • On a SPARC CPU, this dumps core with a bus error.
    • On an ARM7TDMI CPU, this might print something like "7ARM" or "ITDM", assuming that the variable "x" is aligned on a 32-bit boundary (which depends on where "x" is located and what compiler options are in use, etc.) and you are using little-endian mode. It's undefined behavior, but it's pretty much guaranteed not to work the way you want.

提交回复
热议问题