Why doesn’t this valid C program compile?

I wanted to use some C code I found, and when I tried to compile the source, it kept complaining because of a syntax error.

... 
void printMD()
{
printf("ABC ");
int i;
i = 0;
printf("I is %i\n");
}
...

The original code was several thousand lines long. The (first) error message was

ERROR CCN3275 ./perfutic.c:4     Unexpected text 'int' encountered.                                        

There were two challanges

  1. Create the smallest program to isolate
  2. Find out why the code failed to comile

Isolate the problem

I put #ifdef temp…. #endif around blocks of code to remove irrelevant code. This worked, but I quickly got into a mess where I had many #ifdef…#endif and matching them up.

I saved a copy of the program, then used #ifdef..#endif to ignore blocks of code. If this made no change to the compile, then delete the block, and add more #ifdef…#endif. If it caused other error messages, remove the #ifdef..#endif statements, and try a smaller block of code.

Eventually I got down to the code above.

Why did the code fail to compile

I spent half a day scratching my head, and when I came back next morning, I had a flash of inspiration.

Later versions of C were more flexible in some areas.

In early days of the C compiler you had to define all variables before you did any work. With later versions of the C compiler this restriction was relaxed, so you could fall a function, the define a variable.

See intermingled declarations and code: variable declaration is no longer restricted to file scope or the start of a compound statement (block) in the ISO C99 specification

The makefile I was using was

cparms ="-Wc,SO,LIST(lst31),XREF,ILP32,DLL,SSCOM,SHOWINC,DEFINE(MVS=1)"  
cc -c -o $@ -I"//'MQCD94.SCSQC370'" -I'/usr/include' -I. $(cparms) $<

You control the level of C using the LANGLVL option.

The cc command produced( in the listing)

Language level. . . . . . . . : *COMMONC:NOTEXTAFTERENDIF 

With the c99 command, the code compiled, and the listing had

 Language level. . . . . . . . : *STDC99:NOTEXTAFTERENDIF 

With the original compile, I was using the options which did not allow variables to be defined after executable code.

Instead of using cc, I could have used cc with langlvl(EXTENDED).

Why doesn’t this valid C program compile?

The short answer is : I was using the wrong compiler options.

Leave a comment