2009-02-18 57 views
3

首先,我对C++很陌生。我相信getline()不是标准的C函数,所以需要#define _GNU_SOURCE来使用它。现在,我使用C++和g ++告诉我,_GNU_SOURCE已定义:getline()在C++中 - _GNU_SOURCE不需要?

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

谁能确认这是否是标准的,或者它的定义在我的设置隐藏的地方?我不确定引用的最后一行的含义。

该文件的包括如下,所以大概它的定义在一个或多个这些?

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

谢谢!

回答

5

我觉得从版本3开始,g ++自动定义了_GNU_SOURCE

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

如果你不想要它,#undef它作为第一个:这是在错误,指出第一个定义是在命令行上完成(在视线进制-D_GNU_SOURCE)你的第三个行支持在你的编译单元中。您可能需要它,但是,在这种情况下使用:

#ifndef _GNU_SOURCE 
    #define _GNU_SOURCE 
#endif 

你得到错误的原因是因为你重新定义它。如果将其定义为原来的内容,则不应该是错误的。至少C就是这种情况,它可能与C++不同。基于GNU头文件,我会说他们正在做一个隐含的-D_GNU_SOURCE=1这就是为什么它认为你重新定义它到别的东西。

下面的代码片段会告诉你它的值,前提是你没有改变它。

#define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n") 
DBG(_GNU_SOURCE); // first line in main. 
+0

感谢您的回复,为我解决了一些问题。我将按照建议的兼容性使用预处理器。 – Ray2k 2009-02-18 01:37:11

0

我一直不得不在C++中使用下列之一。以前从来没有必要声明_GNU_。我通常在* nix中运行,所以我通常也使用gcc和g ++。

string s = cin.getline() 

char c; 
cin.getchar(&c); 
+1

他意思是这个getline:http://www.gnu.org/software/libtool/manual/libc/Line-Input.html – strager 2009-02-18 01:25:51

0

Getline是标准的,它有两种定义。
如下你可以把它作为一个流的成员函数: 这是

//the first parameter is the cstring to accept the data 
//the second parameter is the maximum number of characters to read 
//(including the terminating null character) 
//the final parameter is an optional delimeter character that is by default '\n' 
char buffer[100]; 
std::cin.getline(buffer, 100, '\n'); 

中定义的版本,或者您可以使用定义的版本

//the first parameter is the stream to retrieve the data from 
//the second parameter is the string to accept the data 
//the third parameter is the delimeter character that is by default set to '\n' 
std::string buffer; 
std::getline(std::cin, buffer,'\n'); 

进一步参考 http://www.cplusplus.com/reference/iostream/istream/getline.html http://www.cplusplus.com/reference/string/getline.html