TIL: Use feature test macros to control defintions exposed in system header files

2022-06-08 00:00:00 +0000 UTC

Feature test macros do what it says in the manpage: allow the programmer to control the definitions exposed by system header files. Immediately following this is a key detail about usage:

In order to be effective, a feature test macro must be defined before including any header files.

I stumbled on this feature through trying to implement the programs described in the getaddrinfo section of Beej’s network programming guide. I kept getting this error:

serv.c:15:18: error: storage size of ‘hints’ isn’t known

struct addrinfo hints, *res, *p;

Even when I copied and pasted the example code exactly from Beej’s provided file! A quick google search revealed the issue: the feature test macro #define _POSIX_C_SOURCE 200112L is required for struct addrinfo to be exposed. Had I checked the man page for getaddrinfo:

Feature Test Macro Requirements for glibc (see

feature_test_macros(7)):

  getaddrinfo(), freeaddrinfo(), gai_strerror():

      Since glibc 2.22:

          _POSIX_C_SOURCE >= 200112L

      Glibc 2.21 and earlier:

          _POSIX_C_SOURCE 

I could have found that myself but didn’t take a moment to check the man pages for the relevant syscalls in the example code!

So I relearned a key lesson–always start with man the-call-related-to-the-problem–and also learned about the -E flag for gcc from this stackoverflow post.

Tags: til c linux