PDA

View Full Version : warning: implicit declaratino of function 'getped'



monkeyking
December 17th, 2008, 02:34 AM
This small snippet


#include <stdio.h>

int main(){
printf("start of main\n");
printf("main pid:%d\n",getpid());
printf("end of main\n");
return 0;
}


Gives me this warning



gcc -Wall -ansi -pedantic fork.c
fork.c: In function ‘main’:
fork.c:6: warning: implicit declaration of function ‘getpid’


I found this strange, if it doesn't know the function,
how can it call it.

The program works though.

htanks in advance

edit.
title should be getpid,

sorry for the typo...

bruce89
December 17th, 2008, 02:38 AM
You need to include unistd.h, as getpid () is defined there.

monkeyking
December 17th, 2008, 02:49 AM
You need to include unistd.h, as getpid () is defined there.
Yes,
but I don't understand why it works without including unistd

bruce89
December 17th, 2008, 02:57 AM
Yes,
but I don't understand why it works without including unistd

Apparently implicit declerations were fine up until C99.

monkeyking
December 17th, 2008, 03:01 AM
But why bother with including anything,
if it always work.

When is it necessary to include stuff.

This seems quite inconsistent.

bruce89
December 17th, 2008, 03:02 AM
But why bother with including anything,
if it always work.

When is it necessary to include stuff.

This seems quite inconsistent.

GCC defaults to C89 mode, so it doesn't bother with implicit declarations unless you activate warnings. If you compile with gcc -std=c99 -o fork fork.c, you get warnings.

dwhitney67
December 17th, 2008, 06:02 AM
GCC defaults to C89 mode, so it doesn't bother with implicit declarations unless you activate warnings. If you compile with gcc -std=c99 -o fork fork.c, you get warnings.
+1

But still, why does the program run? Well, it is because the dependencies are resolved during linking. The GCC (automatically) uses the C standard library (/usr/lib/libc.so and whatever it references), and all is kosher.

The warning(s) are generated by the compiler because it hasn't a clue what the function (e.g. getpid) is defined to be. It just so happens that it is defined to accept no args and return an int. However, if you write an application that passes it a string (and perhaps other args), the compiler will go along with it, but will still not know about getpid (hence the warning).

The args passed to getpid() may affect the application during runtime. I tried passing a const string and two ints, but even that didn't phase it. Maybe I was lucky.

Anyhow, the purpose of including header files is to provide the compiler the definition of the (library) functions that are being used by an application, thus mitigating any potential error in the specified parameters or in the use of the return value.

IMO, using the -Wall (and possibly the -Werror) GCC options are essential to the development of any worthwhile project.