1

Alright, so I've got this programming assignment in C that I've been working on using Pelles C, and everything's going swell so far, but in the end it needs to be running on the university's Unix system. So I try to compile on their Unix and suddenly I'm getting a pile of errors that didn't exist before.

So let's say I've got this as a main function:

#include <stdio.h>

int main (int argc, char* argv[]){
    printf("Hello World");
    int anInt;

    return 0;
}

And I give a compile command...

cc main.c

I get this error:

"main.c", line 5: syntax error before or at: int

...is this one of those cases where there's a common example of a Unix command all over the internet but it's not actually the one you'd ever use? or is Pelles C "filling in the gaps" for me here? or is there just something off with that compiler, or what?

user1299656
  • 630
  • 1
  • 9
  • 15
  • 3
    Probably related to http://stackoverflow.com/questions/288441/variable-declaration-placement-in-c – NG. Jan 26 '14 at 04:24
  • Yeah... that's it. Looks C can be inconsistent on that rule depending on environment/compiler – user1299656 Feb 17 '14 at 05:52

1 Answers1

5

I haven't seen this before. When I tried it on my Ubuntu server, your source code compiled fine. However, when I tried using the -pedantic flag, I received the following error:

hello.c: In function ‘main’:
hello.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wpedantic]
     int anInt;
     ^

So, your solution is to find a compiler that supports a standard later than C90, or to change your source to move declarations before code:

#include <stdio.h>

int main (int argc, char* argv[]){
    int anInt;
    printf("Hello World");

    return 0;
}

More precisely, variables must be declared before code in the block in which they're scoped, so this is valid too:

#include <stdio.h>

int main (int argc, char* argv[]){
    printf("Hello ");

    {
        int anInt;
        printf(" World");
    }
    return 0;
}
millinon
  • 1,528
  • 1
  • 20
  • 31
  • Thanks, that's what was going on. Unfortunately I'm stuck with the compiler I'm stuck with, so I'll have to keep declarations and code separate. – user1299656 Feb 17 '14 at 05:54