1

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:

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).

Is the above code valid C? Or is it valid 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. Any suggestions? Thanks!

L. Scott Johnson
  • 4,213
  • 2
  • 17
  • 28
David
  • 1,847
  • 4
  • 26
  • 35
  • 3
    *Which* errors is it throwing exactly? – Marco Bonelli Oct 30 '20 at 16:48
  • Assuming it's allowed by the language, why does it seem strange? If `somename` is a good name for the structure type, it's also a good name for a member that holds that type. – Barmar Oct 30 '20 at 16:55
  • OTOH, it's conventional to end type names with `_t`. However, you should avoid that in user-defined types, since it's reserved by POSIX. – Barmar Oct 30 '20 at 16:56
  • 2
    Why is this closed? This is a valid question, what error any specific compiler outputs is irrelevant to question as to whether this is valid C code (spoiler: it is). – Peter Oct 30 '20 at 18:09
  • 1
    I agree that the question shouldn’t have been closed. Whoever closed it should reopen it. As for the error: it’s basically as I described. The Arduino IDE is screaming at me that the “somename” symbol was already defined elsewhere in the same scope (which it was), while whatever compiler Atmel uses is not doing so. I assume tue Atmel compiler is a C compiler, while Arduino’s is a C++ compiler. And remember: this isn’t my code, it’s 3rd party code I am trying to bring in. – David Oct 31 '20 at 06:53
  • @Peter: I guess the question was closed for the absence of the **exact error message** in it, which is stated by the very first comment. To OP: Please, add the error message into the question post itself. – Tsyvarev Oct 31 '20 at 10:52
  • The exact error message doesn't matter to the question. The question is simply: is this code valid C or valid C++? Period. Should the compiler allow this code or not? – David Nov 01 '20 at 11:39

1 Answers1

0

Ir is compiling by default as C++ so you need to add -xc command-line option.

As far as I know C++ does not allow the same names for types and objects.

0___________
  • 60,014
  • 4
  • 34
  • 74