简体   繁体   English

#include是在.h文件还是.cpp文件中为什么为什么重要?

[英]why does it matter if the #include are in the .h file or in .cpp file?

I have a cpp file contains this include: 我有一个cpp文件,其中包含:

#include "twitServer.h"

and in twitServer.h I have: 在twitServer.h中,我有:

#ifndef twitServer_twitServer_h
#define twitServer_twitServer_h
#include <string>
#include <map>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <sys/socket.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <netdb.h>
#include <errno.h>
#include <sstream>
#include <algorithm>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "twitUser.h"

using namespace std;

void startServer(string port);

#endif

But the Xcode says for this line: 但是Xcode对此行说:

if ((rv = getaddrinfo(NULL, port, &hints, &ai)) != 0) {
    fprintf(stderr, "selectserver: %s\n", gai_strerror(rv));
    exit(1);
}

that the getaddrinfo is not defined... why that? 没有定义getaddrinfo ...为什么?

if the includes are in the cpp file it works fine how comes 如果包含在cpp文件中,则可以正常工作

不确定如何解决问题,但按照惯例,您绝对不应将其包含在头文件中,因为有一天可能会编写代码,需要头文件,但不是所有包含的内容。

Try including Ws2tcpip.h and see if that solves the problem. 尝试包括Ws2tcpip.h,看看是否可以解决问题。 This is what MSDN has to say about it (see the requirements section) 这就是MSDN要说的(请参阅需求部分)

http://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx http://msdn.microsoft.com/zh-CN/library/windows/desktop/ms738520%28v=vs.85%29.aspx

Also, let me say that this seems like an awful lot of header files included and some should not be matched unless you really know what you are doing. 另外,让我说,这似乎包括了很多头文件,有些不应该匹配,除非您真的知道自己在做什么。 There are quite a bit of C++ headers (iostream (which is included twice by the way), cstdio, cstdlib, algorithm, list, string, ctime...) mixed with C headers (stdio.h, stdlib.h string.h). 有很多C ++头文件(iostream(包括两次),cstdio,cstdlib,算法,列表,字符串,ctime ...)与C头文件(stdio.h,stdlib.h string.h)混合在一起)。 Maybe it's time for some late spring cleaning in there :) 也许是时候在那里进行后期春季清洁了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM