Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need feature test macros?

Tags:

c

linux

By reading What does -D_XOPEN_SOURCE do/mean? , I understand that how to use feature test macros.

But I still don't understand why do we need it, I mean, can we just enable all features available? Then the doc writes like this: this function only available in Mac/BSD, that function only available in Linux, if you use it, then your program can only be running on that system.

So why do we need a feature test macro in the first place?

like image 533
scriptboy Avatar asked Jul 05 '21 17:07

scriptboy


1 Answers

why do we need it, I mean, can we just enable all features available?

Imagine some company has written perfectly fine super portable code roughly like the following:

#include <stdlib.h>
struct someone_s { char name[20]; };

/// @brief grants Plant To someone
int grantpt(int plant_no, struct someone_s someone) {
   // some super plant granting algorithm here
   return 0;
}

int main() {
   // some program here
   struct someone_s kamil = { "Kamil" };
   return grantpt(20, kamil);
}

That program is completely fine and all is working fine, and that program is very C compatible, thus should be portable to anywhere. Now imagine for a moment that _XOPEN_SOURCE does not exist! A customer receives sources of that program and tries to compile and run it on his bleeding edge Unix computer with certified C compiler on a certified POSIX system, and he receives an error that that company has to fix, and in turn has to pay for:

/tmp/1.c:7:9: error: conflicting types for ‘grantpt’; have ‘int(struct someone_s,  int)’
    7 |     int grantpt(struct someone_s someone, int plant_no) {
      |         ^~~~~~~
In file included from /tmp/1.c:2:
/usr/include/stdlib.h:977:12: note: previous declaration of ‘grantpt’ with type ‘int(int)’
  977 | extern int grantpt (int __fd) __THROW;
      |            ^~~~~~~

Looks like a completely random name picked for a function is already taken in POSIX - grantpt().

When introducing new symbols that are not in reserved space, standards like POSIX can't just "add them" and expect the world not to protest - conflicting definitions can and will and do break valid programs. To battle the issue feature_test_macros were introduced. When a program does #define _XOPEN_SOURCE 500 it means that it is prepared for the POSIX standard and there are no conflicts between the code and symbols introduced by POSIX in that version.

Feature test macros are not just "my program wants to use these functions", it is most importantly "my program has no conflicts with these functions", which is way more important, so that existing programs continue to run.

like image 112
KamilCuk Avatar answered Oct 14 '22 20:10

KamilCuk