Casting with the realpath function (c programming)

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 am getting a warning on the line that contains the call to the realpath function, saying:

warning: assignment makes pointer from integer without a cast

      

Does anyone know what? I am running Ubuntu Linux 9.04

+2


source to share


2 answers


It's very simple. Glibc views realpath () as a GNU extension, not a POSIX extension. So add this line:

#define _GNU_SOURCE

      

... before including stdlib.h, so it's prototyped and known to return char *

. Otherwise gcc will assume that it returns the default type int

. The prototype in stdlib.h is not displayed unless defined _GNU_SOURCE

.



The following matches the no-warning penalty with passing -Wall:

#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 (). It's worth looking at / usr / include / to see how many macros are included and what changes.

+4


source


The compiler doesn't know what it is realpath

, so it accepts a function that returns an int. It does this for historical reasons: many older C programs relied on this to do it.



You are probably missing a declaration for example. forgetting #include

its header file.

+2


source







All Articles