سؤال

I've been trying to compile a piece of C code which should create processes using the fork() function.`

#include <stdio.h>
#include <unistd.h>
main()
{
    int n=15, z=20, count=3, mult=1;
    while(count<3)
    {
        if(z!=0)
        {
            z=fork();
            n=n+15;
        }
        else
        {
            z=fork(); n=n+10; mult=mult*n;
        }
        printf(" z=%d   mult=%d",z,mult);
        count=count+1;
    }
}

Compiled with "gcc -Wall -W -Werror main.c -o ProcessCreateC" in the terminal. I'm getting error:

main.c:3:5: error: return type defaults to ‘int’ [-Werror=return-type]
main.c: In function ‘main’:
main.c:20:5: error: control reaches end of non-void function [-Werror=return-type]
cc1: all warnings being treated as errors

Since I only have experience compiling in Windows and have little experience with Linux, I have no idea what is causing this. Any ideas??

هل كانت مفيدة؟

المحلول

Add return 0;or a similar expression that returns an integer, to the end of your main(), and change main() to int main(), and I think you will find that the code works fine.

When no return type is specified for main(), it defaults to int. Furthermore, with the compiler flags you have enabled, not specifying a type for main() causes an error.

نصائح أخرى

The problem is twofold (since all warnings are errors):

  1. main should return int, e.g. actually end with return 0;
  2. you should be explicit about main returning int, i.e. write int main(, not just main(.

You have not mentioned the return type of the main function as void so gcc is defaulting it to an integer return value.

Since GCC follows the ANSI C standard, you have to specify the return type of main as int like:

int main()
{
    //Do stuff
     return 0;
}

It is important to remember standards used by compilers, else you will continue making these mistakes and spend more time debugging rather than doing something productive.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top