简体   繁体   中英

Strange syntax error C2143 in Visual only (missing ';' before 'type')

I'm getting a strange compilation error for a C code in MSVC only. More precisely:

error C2143: syntax error : missing ';' before 'type'

C2143 is a fairly generic error, and there are myriad of questions on SO around it, but none of them seems to apply so far. The closest one can be found here , and stress the importance of declaring variables at the beginning of a block, which seems to have been respected here.

Here is a sample code:

#define       NB_LL 6
typedef struct { long long ll[NB_LL ]; } stateSpace_t;
#define ALLOCATE_ONSTACK(stateName)  stateSpace_t stateName##_s; void* stateName = (void*) &(stateName##_s);

The following code works well:

void f1()
{
    ALLOCATE_ONSTACK(state1);
    /* do something */
}

This one doesn't:

void f2()
{
    ALLOCATE_ONSTACK(state1);
    ALLOCATE_ONSTACK(state2);   // <--- error C2143: syntax error : missing ';' before 'type'
    /* do something */
}

The second code works well with GCC, so the issue seems restricted to MSVC. My understanding is that macro ALLOCATE_ONSTACK() only do variable declaration and initialization, so it seems to respect C syntax.

Is it?

OK, this one is fairly convoluted.

Look at the

#define ALLOCATE_ONSTACK(stateName)

It ends with a ; character.

Now look at your code :

ALLOCATE_ONSTACK(state1);

It also ends with a ';' character. That means that, on this particular line, you have 2 following ';' characters.

Since MSVC is not C99, it requires all declarations to be done at the beginning of the block. Since you have two ';' characters following each other, it acts as if the declaration area was ended. So, when you declare other variables in :

ALLOCATE_ONSTACK(state2);

it then fails, syntax error.

GCC has no such problem since it is C99.

Either remove the ';' character at the end of the macro, or within your source code. Only one is required. Not sure which solution is better...

[Edit] : As suggested in comments and other answer, removing the semicolon from the macro looks the better solution.

You have a semi-colon at the end of the ALLOCATE_ONSTACK macro definition and also at the end of the invocation. This means that you effectively have a null statement after each macro expansion. Because of this, the second expansion is not at the beginning of the block.

Classically, C has required that all declarations occur in a block before the first non-declaration statement. gcc relaxes this requirement so the error doesn't occur.

I'd suggest rewriting your macro definition without the trailing semicolon.

Edit: beat to the punch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM