简体   繁体   English

联合成员名称与其类型名称相同的 C 代码

[英]C code with a union member name the same as its type name

I am currently working on some microcontroller code in C, and one of the third-party libraries I am using has some structs and unions defined in the following manner:我目前正在使用 C 编写一些微控制器代码,我正在使用的第三方库之一具有以以下方式定义的一些结构和联合:

typedef struct
{
    ...members of struct...
} somename;

typedef struct
{
    ...members of struct...
} somename2;

typedef union
{
    somename somename;
    somename2 somename2;
} anothername;

The code compiles in Atmel Studio 7 (not sure what underlying compiler it's using), but it fails to compile in the Arduino IDE (which is using some version of gcc/g++ I believe).代码在 Atmel Studio 7 中编译(不确定它使用的是什么底层编译器),但它无法在 Arduino IDE 中编译(我相信它使用了某些版本的 gcc/g++)。

Is the above code valid C?上面的代码是有效的 C 吗? Or is it valid C++?或者它是有效的C++? Or valid either/neither?或者两者都有效? It seems strange to me that the authors of this code would give the members of this union a variable name that is identical to the type name which happens to be a struct they defined just above in the file.我觉得奇怪的是,这段代码的作者会给这个联合的成员一个变量名,该变量名类型名相同,而类型名恰好是他们在文件中定义的结构体。

Anyway, the Arduino compiler is throwing errors when it reaches this code, so I'm trying to figure out whether it's valid code and how to make the Arduino compiler like it.无论如何,Arduino 编译器在到达此代码时会抛出错误,所以我试图弄清楚它是否是有效代码以及如何让 Arduino 编译器喜欢它。 Any suggestions?有什么建议? Thanks!谢谢!

Ir is compiling by default as C++ so you need to add -xc command-line option. Ir 默认编译为 C++,因此您需要添加-xc命令行选项。

As far as I know C++ does not allow the same names for types and objects.据我所知,C++ 不允许类型和对象使用相同的名称。

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

相关问题 C样式/ C ++正确性,是struct / union / enum标签与类型名称相同吗? - C style/C++ correctness, is struct/union/enum tag same as type name bad in any way? 请求成员以非结构或联合形式的“名称” - request member for 'name' in something not structure or union 错误:在非结构或联合中请求成员“名称” - Error: request for member 'Name' in something not a structure or union 调用成员C ++函数,但C函数具有相同的名称 - call member C++ function but C function has same name C-当不转换为其类型的指针时,数组名称是什么? - C - what is array name when not converted to pointer of its type? C:如何在不提及其类型名称的情况下返回结构文字? - C: how to return a struct literal without mentioning its type name? 错误:成员引用基类型 'candidate[9]' 不是结构或联合合并排序(candidates.votes,0,MAX-1,candidates.name); - error: member reference base type 'candidate[9]' is not a structure or union mergesort(candidates.votes, 0, MAX-1, candidates.name); 将字符串分配给定义为 char name[20] 的联合成员时,它不会编译 - when assigning a string to a union member defined as char name[20] it will not compile 为什么“代码”与“名称”相同? - Why is the "code" the same as the "name"? 如何使用嵌套在struct中的c union没有名称 - How to use c union nested in struct with no name
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM