Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't getaddrinfo be found when compiling with gcc and std=c99

Tags:

c

posix

gcc

I have the following code which I was trying to compile. When I tried with std=c99 it failed with warnings about "implicit declaration of type struct addrinfo" and "implicit declaration of function getaddrinfo". It works with std=gnu99.

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int fails(const char *host, const char *port, struct addrinfo *hints)
{
        int rc;
        struct addrinfo *results;

        // can't find this function??
        rc = getaddrinfo(host, port, hints, &results);

        // free memory in this important application
        freeaddrinfo(results);

        return rc;
}

The commands I used to compile is:

gcc -c -o fail.o -Wall -Werror -std=c99 -save-temps fail.c
gcc -c -o fail.o -Wall -Werror -std=gnu99 -save-temps fail.c

Looking at fail.i (preprocessed header) I see that compiler is right: those types haven't been declared in the headers pulled in.

So I went to the headers and noticed that getaddrinfo is surrounded by a guard #ifdef __USE_POSIX, which is obviously not declared when compiling with c99.

How do I tell gcc that I want to use c99 and POSIX? I don't really want to use gnu99 in case I decide to switch compilers later (eg Clang or icc).

like image 251
dave Avatar asked Aug 19 '12 06:08

dave


1 Answers

Simply because getaddrinfo (POSIX.1g extension) is not part of the standard c99:

http://www.schweikhardt.net/identifiers.html

stay with -std=gnu99 or -D_POSIX_C_SOURCE=200112L

like image 198
TOC Avatar answered Nov 11 '22 03:11

TOC