vs添加curl

转载来自:https://blog.csdn.net/DaSo_CSDN/article/details/77587916/

本文开发环境

Window 10 x64 Enterprise [10.0.17763.475]
下载地址1:https://msdn.itellyou.cn/
下载地址2:https://msdn.rg-adguard.net/public.php
Visual Studio 2017/2019 Enterprise
下载地址:https://www.visualstudio.com/downloads/
libcurl [7.55.1-7.65.1]
下载地址:https://curl.haxx.se/download.html

【警告】
请确保电脑上没有安装2017/2019以外版本的Visual Studio(尤其是2015),否则可能会出现LNK2001错误。

编译

  • 截止本文撰写时(2017年8月25日)官方并未提供适用于Visual Studio的预编译包,因此需要自行编译

打开上方源码下载地址,下载最新版的压缩包。
这里写图片描述
解压,并进入文件夹,运行buildconf.bat
这里写图片描述
本文以编译x64为例
在开始菜单中找到Visual Studio 2017/2019文件夹,编译64位则右击x64 Native Tools Command Prompt for VS 2017/2019,编译32位则右击x86 Native Tools Command Prompt for VS 2017/2019,选择Run as administrator
这里写图片描述
进入curl文件夹中的winbuild文件夹。
这里写图片描述
VS2017/2019+x64+静态编译:
输入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
如果你是VS2017且未更新到最新版,VC=15建议改为VC=14
更详细的编译指令及说明可以打开winbuild文件夹中的BUILD.WINDOWS.txt查看。
这里写图片描述
回车,等待编译完成,关闭控制台界面。
打开curl文件夹中的builds文件夹,将名字最短的文件夹备份,其余文件夹为编译时产生的临时文件,可全部删除。
这里写图片描述
本文将编译生成的文件夹剪切至其他路径,以便长期使用。
这里写图片描述

配置工程

新建一个项目。本文选择新建一个名为Test的空项目。
这里写图片描述
右击项目,选择Properties
这里写图片描述
选择需要的配置。
下图为本文所选择的ConfigurationsPlatform,请自行根据需要选择切换。
这里写图片描述
将编译得到include文件夹和lib文件夹添加至工程。
如果编译了debug版libcurl,则应将debug文件夹中的内容添加至Configurations: Debug
如果编译了x86,则将x86文件夹中的内容添加至Platform: x86
这里写图片描述
将以下lib添加至工程。

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

本文使用了静态编译,所以需要将CURL_STATICLIB添加至工程。
这里写图片描述
本文使用了静态编译且没有编译debug版libcurl,所以直接在Configurations: All Configurations中将Runtime Library选择为/MD
如果编译了debug版libcurl,请分别在Configurations: Debug中选择/MDdConfigurations: Release中选择/MD
如果使用了动态编译,则为/MTd/MT
在这里插入图片描述

测试代码

注意此处设置需要符合刚刚的配置。

#include <curl/curl.h>    

int main(int argc, char* argv[]) {
    CURL *curl = 0;
    CURLcode res;
    curl = curl_easy_init();
    if (curl != 0) {
        curl_easy_setopt(curl, CURLOPT_URL, "https://www.baidu.com");
        
        //www.baidu.com 可能会跳转,所以设置为跟随跳转
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        
        //发出请求
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            //输出可能是乱码,因为没配置UTF-8
            fprintf(stderr, "curl_easy_perform() failed: %s
", curl_easy_strerror(res));        
        }
        
        //清理工作
        curl_easy_cleanup(curl);
    }

    return 0;
}
原文地址:https://www.cnblogs.com/Galesaur-wcy/p/15512187.html