Reputation: 7610
I am doing a sample application where I have declared a struct:
// common.h
typedef struct MyStruct
{
int a;
}
//sample.h
#include "common.h"
int main()
{
MyStruct st;// getting error here
}
C2146: syntax error : missing ';' before identifier
What are the possible reasons for this?
Upvotes: 3
Views: 8857
Reputation: 471209
Two things:
First, you're missing a semi-colon after the struct definition:
// common.h
typedef struct MyStruct
{
int a;
};
^
Not that this is still wrong. You will need to fix the other error.
Second, you should define the struct like this:
// common.h
typedef struct
{
int a;
} MyStruct;
Alternatively, you can define it like this:
// common.h
struct MyStruct
{
int a;
};
Upvotes: 3
Reputation: 881093
It's almost always because the type MyStruct
isn't defined at that point, either because you're including the wrong header or the type specification fails for some reason.
If that typedef is exactly what you have in your common.h
, it won't work. It should be followed by the aliasing type and a semicolon. Or perhaps you didn't want a typedef since C++ allows you to refer to MyStruct
as a "proper" type in the source code.
Something like this works fine:
struct MyStruct { int a; };
int main() {
MyStruct st;
return 0;
}
Or even this, showing the three possibilities:
struct MyStruct { int a; };
typedef struct MyStruct2 { int a; } xyzzy;
int main() {
MyStruct st;
MyStruct2 st2;
xyzzy st3;
return 0;
}
Upvotes: 1
Reputation: 753455
Your "common.h"
header does not define MyStruct
properly; it needs a semi-colon on the end.
Then the typedef
is vacuous; in C++, you don't need the typedef
to get type MyStruct
defined. (In C, you'd need to write:
typedef struct MyStruct { int a; } MyStruct;
But C++ does not require that - though it does not object to it, either.)
So, it would be sufficient to write:
struct MyStruct { int a; };
Upvotes: 1