casting issue with realpath function (c programming)

假如想象 提交于 2019-12-13 16:38:34

问题


When I compile the following code:

#define _POSIX_C_SOURCE 200112L
#define _ISOC99_SOURCE
#define __EXTENSIONS__

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>    

int
main(int argc, char *argv[])
{
    char *symlinkpath = argv[1];
    char actualpath [PATH_MAX];
    char *ptr;
    ptr = realpath(symlinkpath, actualpath);
    printf("%s\n", ptr);
}

I get a warning on the line that contains the call to the realpath function, saying:

warning: assignment makes pointer from integer without a cast

Anybody know what's up? I'm running Ubuntu Linux 9.04


回答1:


This is very simple. Glibc treats realpath() as a GNU extension, not POSIX. So, add this line:

#define _GNU_SOURCE

... prior to including stdlib.h so that it is prototyped and known to to return char *. Otherwise, gcc is going to assume it returns the default type of int. The prototype in stdlib.h is not seen unless _GNU_SOURCE is defined.

The following complies fine without warnings with -Wall passed:

#include <stdio.h>
#include <limits.h>

#define _GNU_SOURCE
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    char *symlinkpath = argv[1];
    char actualpath [PATH_MAX];
    char *ptr;
    ptr = realpath(symlinkpath, actualpath);
    printf("%s\n", ptr);

    return 0;
}

You will see similar behavior with other popular extensions such as asprintf(). Its worth a look at /usr/include/ to see exactly how much that macro turns on and what it changes.




回答2:


The compiler doesn't know what realpath is, so it assumes it's a function returning int. It does this for historical reasons: a lot of older C programs relied on it doing this.

You're probably missing the declaration of it, e.g. by forgetting to #include its header file.



来源:https://stackoverflow.com/questions/1583873/casting-issue-with-realpath-function-c-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!