I know it is a Macro we are passing to a function. How do you explain what is the use of this macro, and in which scenario i have to use this ?.
4 Answers
_GNU_SOURCE enables GNU extensions to the C and OS standards supported by the GNU C library, such as asprintf. Define it when you're using such non-standard functions and macros.
3 Comments
From glibc manual:
Macro: _GNU_SOURCE
If you define this macro, everything is included: ISO C89, ISO C99, POSIX.1, POSIX.2, BSD, SVID, X/Open, LFS, and GNU extensions. In the cases where POSIX.1 conflicts with BSD, the POSIX definitions take precedence.
http://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html
Comments
Whereas applications developed conforming to POSIX.1 - (IEEE 1003.1-2008, ISO/IEC 9945:2009) and / or Single Unix Specification 2008 (ISO/IEC 9945:2009 with X/Open Curses) help ensure how portable your application is. The _GNU_SOURCE will most likely limits source code usage to GNU/Linux and GNU/Hurd systems, unless additional work is done to address the non-portability of such functionality on other platforms.
Some companies, and government / military contracts may require certain platform standards to be used.
If you are developing an Open Source / Free Software application that you wish to be available on multiple Unix and Unix-like systems (including Microsoft Windows NT, 2000, and newer which have a POSIX compatibility available) then limiting your development to POSIX.1 library functions makes this an easier task. Other targets include the free/open BSD platforms NetBSD, FreeBSD, OpenBSD, DragonflyBSD, as well as the commercial Unix systems (Solaris, AIX, HP/UX, etc.) that do not include _GNU_SOURCE functionality.
If you use an altered functionality of a portable function, I can't think of an example but I believe they do exist, it may create subtle bugs in non-GNU platforms.
So in general, if your development is already locked into GNU / Linux and GNU / Hurd then feel free to use such extensions, but avoid such usages for any applications that may be deployed on other Unix and Unix-like operating systems.
I do work on a large-ish code base that has been ported from two other Unix platforms to Linux, and we do use _GNU_SOURCE extensions sparingly, though most of the development is limited to modern POSIX or IEEE 1003.1 / Single Unix Spec and C99 (Standard C Library) standards for future compatibility.
3 Comments
gcc -v to check your version, and cpp -dM </dev/null to look for predefined headers. _GNU_SOURCE is not defined, so as the gcc manual explains extensions that don't conflict with ANSI/ISO standards are allowed by default. _GNU_SOURCE would also allow GNU extensions that modify or conflict with ANSI/ISO standards.