Search code examples
c++embeddedavravr-gccatmega

Is it possible to create a new primitive type in C++ for embedded platforms?


I'm writing my own c++ library for an Atmel ATmega2560 chip from scratch as an exercise to learn how it (and electronics in general) works. As part of this, I want to create a new, fundamental byte type in C++, that isn't just an alias of another type, and has an exact size of 8 bits.

As this is an embedded platform, I want to avoid generating additional instructions for the chip to process as much as possible, which makes classes and structs a poor fit. I know that I could use the char type, but it's size is vaguely defined ("at least one byte", and the size of a byte can vary between platforms) by the C++ standards, and I'm not sure how the AVR platform treats it; though I suspect an unsigned char would be 8 bits, as the majority of the registers are 8 bits. There are also other reasons I'd prefer not to use unsigned char.

Essentially, what I would like to do once my library is operational is something like:

int main()
{
/* PORTB is global object instantiated in my lib that unifies handling the Data Register and Data Direction Register for PORTB pins on the chip. PORTD is similar, just memory addresses of registers are different */
  PORTB.setDDR(0); // All pins are inputs.
  PORTD.setDDR(0xFF); // All pins are outputs.
  byte b = PORTB.read();
  b |= 0b10011000;
  PORTD.write(b);

  return 0;
}

Being able to implicitly cast to/from an int and other fundamental types would be a bonus, but probably not necessary. Is it at all possible to do this, short of forking avr-gcc and writing in a new intrinsic type?

Note: I do have the full data sheet for the ATmega2560, which includes a listing of the instruction set. I'm not afraid to use in-line Assembly if I have to, but would prefer not to for performance (after all, I'm only human) and best-practices reasons.

I was able to find this question, but that's still just aliasing, and offers no control over the actual size of the type. Some of the answers also mention using a Boost lib; I'm not sure Boost works on AVR, and I don't want to rely on other libraries, as that defeats the purpose of writing my own from scratch.


Solution

  • No. All types in C++ are either defined by the standard ("primitive types", but also pointers and functions), extended types defined by the implementation (__int128) or User-Defined Types (classes, structs, unions).