2009-02-18 55 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