Piotr Barejko
Piotr Barejko

Reputation: 658

extern struct forward declaration

I am trying to compile some old code that include a mix of C and C++. I found following syntax:

extern struct Edge;
typedef struct Edge
{
    ...
    Edge* edges;
    ...
} Edge;

When I try to compile with GCC I get an error:

a storage class can only be specified for objects and functions extern struct Edge;

After I remove extern it compiles. I might be mistaken, but it does look to me like a forward declaration of Edge, but why there an extern keyword at the front of struct?

Upvotes: 3

Views: 2344

Answers (2)

Piotr Barejko
Piotr Barejko

Reputation: 658

I installed and tested other most popular compilers. Aforementioned code:

  • does NOT compile with GCC-7.3.0 and produces following error:

main.cpp:1:1: error: a storage class can only be specified for objects and functions extern struct Edge; ^~~~~~

  • compiles using clang-6.0 and produces following warning:

main.cpp:1:1: warning: 'extern' is not permitted on a declaration of a type [-Wmissing-declarations] extern struct Edge;

  • compiles using Visual Studio 2017 and produces following warning:

warning C4091: 'extern ': ignored on left of 'Edge' when no variable is declared

Upvotes: 0

user743382
user743382

Reputation:

In C, extern struct S; is valid but not useful: it means exactly the same thing as struct S; In extern struct S a, b, c, ...;, extern applies to a, b, c, ... regardless of how many variables are declared, even if zero variables are declared.

In C++, extern struct S; is invalid. For compatibility with C, most C++ compilers allow it as an extension, but GCC doesn't. You were right to just remove the extern keyword.

It's possible that code originally written extern struct S s; was split up into separate declarations for struct S and s, and extern was accidentally left in. Since the compiler didn't mind, the author didn't notice.

Upvotes: 4

Related Questions