Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline() in C++ - _GNU_SOURCE not needed?

Tags:

c++

getline

Firstly, I'm pretty new to C++. I believe that getline() isn't a standard C function, so #define _GNU_SOURCE is required to use it. I'm now using C++ and g++ tells me that _GNU_SOURCE is already defined:

$ g++ -Wall -Werror parser.cpp
parser.cpp:1:1: error: "_GNU_SOURCE" redefined
<command-line>: error: this is the location of the previous definition

Can anyone confirm if this is standard, or is its definition hidden somewhere in my setup? I'm not sure of the meaning of the final line quoted.

The file's includes are as follows, so presumably it's defined in one or more of these?

#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <list>
#include <sstream>

Thanks!

like image 763
Ray2k Avatar asked Mar 13 '26 13:03

Ray2k


1 Answers

I think g++, from version 3, automagically defines _GNU_SOURCE. This is supported by your third line in the error stating that the first definition was done on the command line (with nary a -D_GNU_SOURCE in sight):

<command-line>: error: this is the location of the previous definition

If you don't want it, #undef it as the first line in your compilation unit. You may need it, however, in which case use:

#ifndef _GNU_SOURCE
    #define _GNU_SOURCE
#endif

The reason you're getting the error is because you're re-defining it. It shouldn't be an error if you define it to what it already was. At least that's the case with C, it may be different with C++. Based on the GNU headers, I would say they're doing an implicit -D_GNU_SOURCE=1 which is why it thinks you're re-defining it to something else.

The following snippet should tell you its value provided you haven't changed it.

#define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n")
DBG(_GNU_SOURCE); // first line in main.
like image 76
paxdiablo Avatar answered Mar 16 '26 01:03

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!