开发者

Is exit() function declared anywhere else besides stdlib.h?

When trying to compile the example below, I received a warning:

>gcc -o file file.c
file.c: In function ‘main’:
file.c:12: warning: incompatible implicit declaration of built-in function ‘exit’

After some search, I realized that example was missing statement #include <stdlib.h>. Where was then exit() function declared? Library stdio.h does not declare it. Neither does my code. If it is supported by compiler, why then it gives a warning? Also, why is it redefined in stdlib.h?

Example:

#include <stdio.h>

int main()
{
    char *fn = "./test.txt";
    FILE *fp;

    if((fp = fopen(fn, "w"))==NULL)
    {
        printf("Cannot open file '%s' for writing.\n", fn);
        exit(1);
    }

    fprintf(fp, "Hello, world!\n");

    if(fclose(fp)==0)
        printf("File '%s' closed successfully.\n", fn);
    else
        pri开发者_StackOverflowntf("Error closing file '%s'.\n", fn);

    return 0;    
}


GCC knows about the contents of the standard headers even when you don't include them, and complains when the implied (or inferred) declaration of the function isn't sufficiently the same as what it would be if the header is included.

By inference, the type of exit() is:

extern int exit();  // Indeterminate argument list

This is not the same as the official declaration:

extern void exit(int);

Hence the warning. Get used to it; fix the code.


[The weasel word 'sufficiently' is there because this code compiles without warning when the declaration of exit() is not commented out, but generates the warning when it is missing.

extern void exit();
int main(int argc, char **argv)
{
    if (argc > 1 && argv[0] != 0)
        exit(1);
    return(0);
}

End of weasel words.]


Note: pre-standard C heavily used implicit function declarations. C89 started to encourage the use of proper definitions, in part by ensuring that every standard function had a header that declared it. (POSIX helped too by ensuring that all the functions it defines are declared in a header.) C99 moved one step further by saying that the pre-standard and C89 'implicit int' interpretation of functions was no longer valid. GCC is now helping you get around to fixing your code by identifying the functions. You can use the options:

-Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition

to help you catch the problems if (like me) you work on antiquated code bases that have not been overhauled to modern C coding standards.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜