cfor-loopgccprogram-entry-point

Trying to compile a C program


I've made a simple C program and I try to compile it using gcc compiler. But when I execute gcc test.c -o test it throws some errors:

test.c:1:19: error: cstdlib: No such file or directory
test.c:2:20: error: iostream: No such file or directory
test.c: In function ‘main’:
test.c:8: error: ‘for’ loop initial declaration used outside C99 mode

And my C program is very simple so I don't think the problem is in the code:

#include <cstdlib>
#include <iostream>

int main(int args, char **argv){
    int result[500];

    for (int i = 0; i < sizeof(result); ++i){
        result[i] = 1;
    }

    return 0;
}

Solution

  • The .c extension means that GCC is interpreting the source files as C code. Your header includes are C++ headers though, and so the C compiler gives you those first two errors. To fix this you can either:

    Or:

    As for the for loop error, the problem is that you've declared the variable i within the initialization step of the for loop. This isn't allowed prior to C99, and so you can fix this by moving the declaration of i to above the loop.

    So the working program might look like this:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(int args, char **argv){
        int result[500];
        int i;
    
        for (i = 0; i < sizeof(result)/sizeof(result[0]); ++i){
            result[i] = 1;
        }
    
        return 0;
    }
    

    In this case I left the header includes in the program, even though they aren't needed. stdio.h is the closest to iostream you can get in C.

    As pointed out by others, for proper behaviour the for loop condition should also be changed to something like i < sizeof(result)/sizeof(result[0]).

    This is because sizeof, when used with an array, gives the size of the array in bytes, which depending on your platform will most likely mean you get the wrong number of iterations in your loop. (An int is typically going to be four bytes, and so the way you've written it your loop would iterate 2000 times instead of 500. By dividing through by the size of one element of your array, you get the right result every time.)

    An even better approach might be to #define the magic number of 500 at the start of your program, and refer to it that way whenever it is needed.

    Overall the main problem is that what you really have is a C++ program, but you're wanting it to be a C program. You'll have to make up your mind as to which language you really want to use.