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
source to share
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.
source to share