简体   繁体   English

如何编写与编译器无关的通用代码?

[英]How to write generic compiler-independent code?

In my work I work with many different compilers for many platforms (Windows, embedded microcontrollers, Arduino, etc). 在我的工作中,我使用用于许多平台(Windows,嵌入式微控制器,Arduino等)的许多不同的编译器。 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. 它主要是低级的东西,所以我想使用'byte','word','bool'等类型。

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. 我了解到typedef比#define更受青睐。 And in this question it is made clear that there is no way to make a conditional typedef. 这个问题中 ,很明显没有办法进行条件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++. 所有平台均应支持bool因为它是C ++中内置类型的保留关键字。

The only platform I know of that has byte and word is Arduino. 我知道的唯一具有byteword是Arduino。 They are just typedef'ed aliases to uint8_t and unsigned int respectively. 它们分别是uint8_tunsigned int typedef别名。 ( 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: 如果您已有使用byteword Arduino代码,最简单的解决方案是检查您的代码是否在Arduino环境中运行,如果不是,请自行定义Arduino类型:

#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. 但是,我的首选解决方案是在需要特定位数时直接使用stdint.h的标准整数。 Using byte and word just adds to the confusion, because it is non-standard. 使用byteword只会增加混乱,因为它是非标准的。 uint16_t tells you exactly what it is, you know exactly what the largest possible value is, and whether it's signed or not. uint16_t告诉您确切的含义,您会确切知道最大的可能值,以及是否已签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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