NO

Author Topic: Compiler Reports Error When Including a Struct Type in Another Struct  (Read 1802 times)

rboni1962

  • Guest
The error occurs even though enabling Microsoft and Pelles C extensions.
Below the code snippet and where the error occurs.

/* File    : main.c                                                         */

#define WIN32_LEAN_AND_MEAN  /* speed up compilations */
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include <tchar.h>

#define NELEMS(a)  (sizeof(a) / sizeof((a)[0]))

struct str1
{
   int i;
   float f;
};

struct str2
{
   char   c;
   str1   st1;   //error #2001: Syntax error: expected '}' but found 'str1'.
};

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2096
Re: Compiler Reports Error When Including a Struct Type in Another Struct
« Reply #1 on: November 09, 2018, 04:53:02 PM »
This is not a bug.
In ISO standard compliant C the structures namespace must be prefixed by the 'struct' keyword, while in C++ a structure definition is automatically inserted in the global namespace.
You should modify your source as follows:
Code: [Select]
struct str1
{
   int i;
   float f;
};
struct str2
{
   char   c;
   struct str1   st1;  //prefix the 'struct' namespace
};

Or, as alternative, to keep the C++ style you can 'typedef' your structure definition. When using 'typedef' in a definition the name of the defined type is saved in the global namespace:
Code: [Select]
typedef struct str1
{
   int i;
   float f;
} str1;
struct str2
{
   char   c;
   str1   st1;  //str1 is defined in global namespace now
};

Using non fully standard compliant compilers, as MSVC, people get accustomed to the wrong behavior.  >:(
It is better to be hated for what you are than to be loved for what you are not. - Andre Gide

rboni1962

  • Guest
Re: Compiler Reports Error When Including a Struct Type in Another Struct
« Reply #2 on: November 11, 2018, 06:51:23 PM »
Thanks Frankie!!!