user1299656
user1299656

Reputation: 650

Error message with Unix compiler only

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?

Upvotes: 1

Views: 136

Answers (1)

millinon
millinon

Reputation: 1576

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;
}

Upvotes: 5

Related Questions