0

我一直在使用 C++ 的 TCP 套接字教程,并遇到以下行 -

在我们开始之前,您需要包含 winsock.h 并将 libws2_32.a 链接到您的项目,以便使用 TCP/IP 所需的 API。如果这不可行,请使用 LoadLibrary() 在运行时加载 ws2_32.dll,或使用一些类似的方法。

经过一番研究,我发现一个声称可以通过以下两行来完成的消息来源 -

#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")

但是,两者中的一个似乎不起作用(我认为这将是第二行,因为第一行相当简单)。这是我要运行的代码-

#include <iostream>
#include <winsock.h>
#pragma comment(lib, "ws2_32.lib")

int main() {
    std::cout << gethostbyname("www.google.com") << std::endl;
    return 0;
}

此代码应打印 Google 的 IP 地址,但会出现以下错误 -

C:\Users\Owner\AppData\Local\Temp\ccOXoE0F.o:SC.cpp:(.text+0x1e): 未定义对 'gethosebyname@4' 的引用

collect2: ld 返回 1 个退出状态

更多谷歌搜索显示,其原因是库的链接不正确。根据这些消息来源,链接它的唯一方法是通过 IDE。我通常将 Notepad++ 与命令提示符一起使用,因此我询问是否可以在不使用 IDE 的情况下正确链接此存档。

如果不可能,那么看来我将不得不重新开始使用 IDE。

4

1 回答 1

0

No, IDEs have nothing to do with this, and your desire is correct and entirely understandable. Since you seem to be on Windows, I'm not sure what kind of command-line toolchain you are using, but if it's one of the GNU-compatible ones (GCC with MinGW, for example), then you can specify the -lws2_32 linker flag to link against the library.

于 2013-03-30T23:51:15.487 回答