0

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??

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 3
    Apart from the language-level errors, if you initialise `count = 3`, the `while(count<3)` loop won't run. – Daniel Fischer Jan 21 '13 at 20:05
  • 1
    Don't forget the `\n` at end of `printf` format string (and perhaps even call `fflush(NULL);` before every `fork`). And you should test the result of `fork`; it can fail! – Basile Starynkevitch Jan 21 '13 at 20:29

3 Answers3

2

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.

PinkElephantsOnParade
  • 6,452
  • 12
  • 53
  • 91
0

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(.
Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
0

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.

varagrawal
  • 2,909
  • 3
  • 26
  • 36