|
|
View previous topic :: View next topic |
Author |
Message |
allenhuffman
Joined: 17 Jun 2019 Posts: 552 Location: Des Moines, Iowa, USA
|
Initializing union elements inside a structure |
Posted: Thu Apr 01, 2021 11:53 am |
|
|
We ran into an issue today where we have a structure containing a union, such as this:
Code: |
#include <UnionInStruct.h>
typedef struct
{
int x;
int y;
} TwoStruct;
typedef struct
{
int a;
int b;
int c;
int d;
} FourStruct;
typedef struct
{
union
{
// This won't work:
TwoStruct two;
FourStruct four;
// But this will:
//FourStruct four;
//TwoStruct two;
} UN;
} ConfigStruct;
// Initialize structure:
ConfigStruct config =
{
{ 1, 2, 3, 4 } // Using four element union
};
void main()
{
while(TRUE)
{
//TODO: User Code
}
}
|
When the structure contains a union, and you try to declare an instance of it, the compiler checks the declaration against the first element of the union. Thus, if you have a union that contains a struct with 2 items, followed by a struct of 4 items, and try to declare an instance with four items, it will fail.
If you swap the union so the four items is first, it will work.
Is there some kind of #pragma or something that would tell the CCS compiler you are trying to declare a specific part of the union rather than it using the first?
We found this in the WizPro I/O library code, which builds under GCC but failed on CCS until we flipped the order of the union.
Cheers! _________________ Allen C. Huffman, Sub-Etha Software (est. 1990) http://www.subethasoftware.com
Embedded C, Arduino, MSP430, ESP8266/32, BASIC Stamp and PIC24 programmer.
http://www.whywouldyouwanttodothat.com ? |
|
|
jeremiah
Joined: 20 Jul 2010 Posts: 1348
|
|
Posted: Fri Apr 02, 2021 12:03 pm |
|
|
I think this is a C language rule, only the first member of a union can be initialized in that way, so make sure to set it up in a way that works for you or else you will need to individually set all the fields.
Later versions of C added the ability to initialize via member names, but CCS is based off of K&R C with some ANSI updated.
You could request from CCS support (via email) a feature addition to update its union initialization to include new versions of C options, such as:
Code: |
union { /* ... */ } u = { .any_member = 42 };
|
Last edited by jeremiah on Fri Apr 02, 2021 12:09 pm; edited 1 time in total |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19510
|
|
Posted: Fri Apr 02, 2021 12:08 pm |
|
|
After C99 (which is later than CCS supports), you can explicitly force
an initialisation of later element, but this requires a designator. Won't
happen automatically. |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|