2011-07-19 137 views
5

我在編譯C++ UDP客戶端程序時遇到了一個奇怪的編譯器錯誤。C++編譯器錯誤「未在此範圍內聲明」

g++ -o client Udp.cpp ClientMain.c -I. -lpthread

In file included from ClientMain.c:1:0:

Udp.h: In destructor ‘CUdpMsg::~CUdpMsg()’:

Udp.h:103:43: error: ‘free’ was not declared in this scope

Udp.h: In member function ‘void CUdpMsg::Add(in_addr_t, const void*, size_t)’:

Udp.h:109:34: error: ‘malloc’ was not declared in this scope

Udp.h:109:41: error: ‘memcpy’ was not declared in this scope

ClientMain.c: In function ‘int main(int, char**)’:

ClientMain.c:28:57: error: ‘memcpy’ was not declared in this scope

ClientMain.c:29:61: error: ‘printf’ was not declared in this scope

ClientMain.c:30:17: error: ‘stdout’ was not declared in this scope

ClientMain.c:30:23: error: ‘fflush’ was not declared in this scope

ClientMain.c:34:68: error: ‘printf’ was not declared in this scope

ClientMain.c:35:17: error: ‘stdout’ was not declared in this scope

ClientMain.c:35:23: error: ‘fflush’ was not declared in this scope

ClientMain.c:37:30: error: ‘usleep’ was not declared in this scope

我在我的cpp文件的開頭聲明瞭以下內容。

#include <netinet/in.h> 
#include <netdb.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <stdio.h> 
#include <arpa/inet.h> 
#include <fcntl.h> 
#include <ifaddrs.h> 
#include <net/if.h> 
#include <cstdlib> 
#include <string> 
#include <stdlib.h> 
#include <cstring> 

#include <errno.h> 

像「的memcpy」函數應該string.h中聲明......我把它(和字符串和CString的)所有申報,而我仍然得到這些編譯器錯誤。有沒有人有線索爲什麼會發生這種情況?謝謝。

+2

你說你在你的*「cpp」*文件中包含這些內容,但錯誤在'ClientMain.c'中(注意'.c',而不是'.cpp')? –

+0

我想你需要在'UDP.h'中包含這些文件中的一部分 – Djole

+0

是你爲這個函數調用的std命名空間 – triclosan

回答

4

如果您有多個文件,那麼您需要在每個文件中包含相應的文件。也許它不在命名空間內?

5

您的Udp.h文件需要包括所需的系統標頭。此外,由於您使用cstringcstdlib作爲您的包含,因此您需要使用std::來限定所有C庫函數,因爲它們的不是通過這些標頭自動導入到全局名稱空間中。

+0

或者它們必須包含在所有翻譯單元中的'Udp.h'之前(儘管如此,這將是不好的做法)。 –

0

一個更清潔的解決方案可能是將CUdpMsg::~CUdpMsg的實現從udp.h移動到udp.cpp,並且類似的任何函數都會給你這樣的錯誤。只有在頭文件中定義函數時,如果它們非常簡單(例如getters)。

5

馬克B涵蓋了錯誤的所有確切原因。我只想補充一點,你應該儘量不要在一個cpp文件中混合兩種C頭文件(#include <cHEADER> vs #include <HEADER.h>)。

#include <cHEADER>變種將所有包含的聲明引入std :: namespace。 #include <HEADER.h>文件包含聲明不包含。當您需要std::malloc()但是::strncpy()時,維護代碼很煩人。爲每個文件選擇一種方法,或者更優選地,爲整個項目選擇一種方法。

作爲一個單獨的問題,您遇到了一種情況,其中標題本身不包含它所需的所有內容。這可能會令人討厭,因爲錯誤可能會出現或消失,具體取決於包含排序。

如果你創建一個頭/ cpp對,總是把匹配的頭作爲cpp文件中的第一個頭,這樣可以保證頭是完整的並且可以獨立運行。如果您創建了一個不需要實現的獨立頭文件,您仍然可以創建一個空的.cpp文件來測試頭文件的包含完整性,或者僅通過編譯器本身運行頭文件。用你創建的每個標題做這件事,可以防止你目前的頭痛。