【问题标题】:Linker errors compiling code using windns.h with gcc [duplicate]使用带有 gcc 的 windns.h 编译代码的链接器错误 [重复]
【发布时间】:2019-03-09 20:07:21
【问题描述】:

我正在尝试在 C 中执行简单的 DNS 查找。这是我的代码(我主要从示例中复制):

#include <winsock2.h>
#include <windns.h>
#include <stdio.h>

char* DNS_Lookup(char* host) {
    DNS_STATUS status;               //Return value of  DnsQuery_A() function.
    PDNS_RECORD pDnsRecord;          //Pointer to DNS_RECORD structure.
    PIP4_ARRAY pSrvList = NULL;      //Pointer to IP4_ARRAY structure.
    WORD wType;                      //Type of the record to be queried.
    char* pOwnerName = host;         //Owner name to be queried.
    char pReversedIP[255];           //Reversed IP address.
    char DnsServIp[255];             //DNS server ip address.
    DNS_FREE_TYPE freetype;
    freetype = DnsFreeRecordList;// DnsFreeRecordListDeep;
    IN_ADDR ipaddr;

    status = DnsQuery(pOwnerName,                 //Pointer to OwnerName. 
                        wType,                      //Type of the record to be queried.
                        DNS_QUERY_BYPASS_CACHE,     // Bypasses the resolver cache on the lookup. 
                        pSrvList,                   //Contains DNS server IP address.
                        &pDnsRecord,                //Resource record that contains the response.
                        NULL);                     //Reserved for future use.
    if(status) {
        printf("Failed to query the host record for %s and the error is %d \n", pOwnerName, status);
    } else {
        ipaddr.S_un.S_addr = (pDnsRecord->Data.A.IpAddress);
        printf("The IP address of the host %s is %s \n", pOwnerName,inet_ntoa(ipaddr));

        // Free memory allocated for DNS records. 
        DnsRecordListFree(pDnsRecord, freetype);
    }
    LocalFree(pSrvList);
    return inet_ntoa(ipaddr);
}

当我尝试编译时,我得到了链接器错误(为了便于阅读,我已经清理了一点):

gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -w
c:/<..>/mingw32/bin/ld.exe: <..>/ccRVIgMi.o: in function `Z10DNS_LookupPc':
../dns.c:17: undefined reference to `DnsQuery_A@24'
c:/<..>/mingw32/bin/ld.exe: <..>/dns.c:30: undefined reference to `DnsRecordListFree@8'
collect2.exe: error: ld returned 1 exit status

我知道为了使用 winsock2.h 编译代码,我必须将 -lws2_32 添加到我的 gcc 命令中,我猜我必须做一些类似于使用 windns.h 编译代码的事情,但我一直无法在线查找任何帮助。

【问题讨论】:

  • 您需要将 Dnsapi.lib 添加到链接器输入
  • @RbMm 我也发现了。谢谢!

标签: c windows winapi gcc


【解决方案1】:

正确答案应该是

 gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -ldnsapi -w

但正如您所发现的那样,它不起作用。谢天谢地gcc 足够聪明,可以提供恢复的方法:

 gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -ldnsapi.dll -w

如果由于某种原因不起作用并且您在 Windows 上进行编译而不是交叉编译,这将起作用:

 gcc -g main.c dns.c -o build.exe -D WIN -lws2_32 -lc:\windows\system32\dnsapi.dll -w

【讨论】:

  • 谢谢!我实际上可以只使用-ldnsapi 编译,最后没有.dll
  • @FelisPhasma:在您(已删除)的自我回答中错字了?无论如何,它对我不起作用,所以我拼写了很长的路。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
相关资源
最近更新 更多