0

For the program

#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>

int main()
{
    pid_t var1;
    int retVal, retStat;

    printf("Program Started. Process PID = %d\n", getpid());

    var1  = fork();

    if(var1 < 0)
    {
        perror("Fork failed\n");
        return 0;
    }
    else if(var1 == 0)
    {
        printf("Child process with pid = %d is executing\n", getpid());
        printf("The var1 value in %d PID process is %d, my parent is %d\n", getpid(), var1, getppid());
    }
    else
    {
        printf("Process with pid = %d is executing\n", getpid());
        printf("The var1 value in %d PID process is %d\n", getpid(), var1);
        // wait(NULL);
        retVal = wait(&retStat);
        printf("Return status of child process is %d\n", retStat / 256);
        printf("Return value for wait is %d\n", retVal);
    }

    printf("Process with PID = %d completed\n", getpid());

    return 3;
}

I get the following warning - warning: implicit declaration of function ‘wait’ [-Wimplicit-function-declaration]

But the program still compiles and the wait function works correctly. I checked in the libraries that I included and there is no definition for wait in any of them. I know that the wait syscall is defined in sys/wait.h. I just want to know how does this program work correctly even after no declaration for wait().

  • From : http://www.unix.org/version3/sample/basedefs/stdlib.h.html: _Inclusion of the header may also make visible all symbols from , , , and _ You can check if this is your case following the `include`s in `"/usr/include/stdlib.h"` – David Ranieri Oct 10 '20 at 10:09

2 Answers2

1

how does this program work correctly even after no declaration for wait()

There is no guarantee that your program runs correctly. The compiler is assuming that wait() is a function with the (implicit) signature int wait(), that is: a function returning an int and taking any argument. Calling a function violating its signature is both an ABI violation and a C standard violation (undefined behavior).

The C library is then linked and at runtime your program might end up working just fine because the dynamic loader is able to find wait() and call it, and the real signature is pid_t wait(int *) (on most systems int wait(int *)), which is not that different from the implicitly assumed one. However, in general, this is not the case.

For more information, see: Implicit function declarations in C

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

C up until C99 allowed implicit declaration of functions. Meaning any function without a declaration will be considered to return an int and be suitable for your call.

The function wait actually have that kind of signature, so in the linkage phase the linker found the function wait in the default linked libraries.

Check this answer for more information/examples

Pablo Yaggi
  • 1,061
  • 5
  • 14