简体   繁体   中英

How to write generic compiler-independent code?

In my work I work with many different compilers for many platforms (Windows, embedded microcontrollers, Arduino, etc). Now I want to write a generic routine that should work with all of them, but I'm getting conflicts with data types. It's mostly low-level stuff, so I would like to work with types like 'byte', 'word', 'bool' etc.

For some compilers these types are not yet defined, but for some they are and in these cases that will result in errors of conflicting types.

I have learned that typedef are prefered above #define. And in this question it is made clear that there is no way to make a conditional typedef.

I already thought of using unique types like for example:

typedef unsigned char mybyte
typedef unsigned short int myword
etc...

But that would make my sourcecode look very ugly IMHO.

All platforms should support bool as it is a reserved keyword for a built-in type in C++.

The only platform I know of that has byte and word is Arduino. They are just typedef'ed aliases to uint8_t and unsigned int respectively. ( Source )

If you have existing Arduino code that uses byte and word , the easiest solution would be to check if your code runs in the Arduino environment, and define the Arduino types yourself if that's not the case:

#ifdef ARDUINO
#include <Arduino.h>
#else
#include <cstdint>
typedef uint16_t word; // or unsigned int, depending on your needs
typedef uint8_t byte;
#endif

However, my preferred solution is to just use the standard integers of stdint.h directly when I need a specific number of bits. Using byte and word just adds to the confusion, because it is non-standard. uint16_t tells you exactly what it is, you know exactly what the largest possible value is, and whether it's signed or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM