2011-07-19 136 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文件来测试头文件的包含完整性,或者仅通过编译器本身运行头文件。用你创建的每个标题做这件事,可以防止你目前的头痛。