Compiler Reports Error When Including a Struct Type in Another Struct

Started by rboni1962, November 09, 2018, 02:41:08 PM

Previous topic - Next topic

rboni1962

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'.
};

frankie

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:

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:

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