【C++开源库】Windows 下编译 libcurl 库

发布时间 2023-07-12 15:11:21作者: Koshkaaa

What is libcurl ?

libcurl 是一个跨平台的网络协议库,支持 http, https, ftp, gopher, telnet, dict, file, 和 ldap 协议。libcurl 同样支持 HTTPS 证书授权,HTTP POST, HTTP PUT, FTP 上传, HTTP 基本表单上传,代理,cookies 和用户认证。想要知道更多关于 libcurl 的介绍,可以到官网 http://curl.haxx.se/上去了解,在这里不再详述。

How install libcurl with Windows and VS2013 ?

libcurl 没有提供编译好的库,需要自己编译,先下载 libcurl 源代码。下载方式:

笔者这里选择官网下载,下载最新版本为 curl-8.1.2,我是 Windows 平台,所以选 zip 文件。

下面介绍 3 种编译方法:

nmake 编译

(1)下载完成后解压,并进入文件夹,运行buildconf.bat

(2)在开始菜单中找到 Visual Studio 2019 文件夹,编译 64 位则右击 x64 Native Tools Command Prompt for VS 2017/2019,编译 32 位则右击 x86 Native Tools Command Prompt for VS 2017/2019,选择管理员方式运行。

(3)进入 curl 文件夹中的 winbuild 文件夹。

(4)2019 + x64 + release + 静态编译:

nmake /f Makefile.vc mode=static VC=15 MACHINE=x64 DEBUG=no
  • 如需动态编译,将 mode=static 改为 mode=dll。(本文仅演示静态编译,同时 curl 官方也不建议使用动态编译)
  • 如需编译为 x86,将 MACHINE=x64 改为 MACHINE=x86。
  • 如需编译为debug版,将DEBUG=no改为DEBUG=yes。
  • 如果你是 VS2019,VC=15 建议改为 VC=14。
  • 更详细的编译指令及说明可以打开 winbuild 文件夹中的 BUILD.WINDOWS.txt 查看。

(5)回车,等待编译完成,关闭控制台界面。编译出的库路径为 C:\Users\xianf\Downloads\curl-7.76.1\builds\libcurl-vc15-x64-release-static-ipv6-sspi-schannel

详细图文教程请参考:Visual Studio(VS2017/VS2019)编译并配置C/C++-libcurl开发环境

nmake 是 Microsoft Visual Studio 中的附带命令,需要安装 VS,即 Windows 上的 make。

如果不了解各个 VS 命令提示工具的区别,可以去看:VS 命令提示工具

Project Setting

(1)新建一个项目。本文选择新建一个名为 Test 的空项目,修改为 Release + x64 配置;

(2)配置 include 和 lib 路径,将以下 lib 添加至工程:

libcurl_a.lib
Ws2_32.lib
Wldap32.lib
winmm.lib
Crypt32.lib
Normaliz.lib

(3)属性 -> 高级 -> 字符集下拉框,使用多字节字符集;

(4)本文使用了静态编译,所以需要将 CURL_STATICLIB 添加至工程;

(5)本文使用了静态编译且没有编译 debug 版 libcurl,所以直接在 Configurations: All Configurations 中将 Runtime Library 选择为 /MD

  • 如果编译了 debug 版 libcurl,请分别在 Configurations: Debug 中选择 /MDdConfigurations: Release 中选择 /MD
  • 如果使用了动态编译,则为 /MTd/MT

Code Test

#include <curl/curl.h>    

int main(int argc, char* argv[]) {
    CURL* curl = nullptr;
    CURLcode res;
    curl = curl_easy_init();
    if (curl != nullptr) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://www.baidu.com");
        /* example.com is redirected, so we tell libcurl to follow redirection */
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        /* Perform the request, res will get the return code */
        res = curl_easy_perform(curl);
        /* Check for errors */
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        /* always cleanup */
        curl_easy_cleanup(curl);
    }

    return 0;
}

Reference