理解_GNU_SOURCE与代码可移植性

Last Updated: 2023-11-05 08:21:23 Sunday

-- TOC --

简单说,就是尽量不要定义_GNU_SOURCE这个宏,存在代码可移植性方面的问题。

下面这段是来自Stack Overflow的回答:

Defining _GNU_SOURCE has nothing to do with license and everything to do with writing (non-)portable code. If you define _GNU_SOURCE, you will get:

  1. access to lots of nonstandard GNU/Linux extension functions
  2. access to traditional functions which were omitted from the POSIX standard (often for good reason, such as being replaced with better alternatives, or being tied to particular legacy implementations)
  3. access to low-level functions that cannot be portable, but that you sometimes need for implementing system utilities like mount, ifconfig, etc.
  4. broken behavior for lots of POSIX-specified functions, where the GNU folks disagreed with the standards committee on how the functions should behave and decided to do their own thing.

翻译:

定义_GNU_SOURCE后,与license没有任何关系,一切只与代码可移植性有关,如果定义了这个_GNU_SOURCE:

  1. 可以访问很多非标扩展接口;
  2. 可以访问很多传统的接口,但没有在POSIX中定义(没有定义的原因,常常是因为在POSIX中有更好的替代);
  3. 可以访问一些底层的但是没有可移植性的接口;
  4. 因为GNU那帮人与POSIX有分歧,他们决定自己干,于是定义了一些接口出来。

As long as you're aware of these things, it should not be a problem to define _GNU_SOURCE, but you should avoid defining it and instead define _POSIX_C_SOURCE=200809L or _XOPEN_SOURCE=700 when possible to ensure that your programs are portable. In particular, the things from _GNU_SOURCE that you should never use are #2 and #4 above.

编写可移植的代码是很重要的,能不用_GNU_SOURCE,就别折腾....

本文链接:https://cs.pynote.net/sf/linux/prog/202207141/

-- EOF --

-- MORE --