笔者在产品开发过程中需要用到https通讯,移植libcurl中遇到很多问题,经过搜索和实践总结一个行之有效的方案,特总结系统对大家有所帮助
1. 环境搭建:
libcurl: curl - Download
VS: Visual Studio 2022, 并安装好本地开发的C++, MFC桌面开发SDK
2. LIB库编译
打开VS2022命令行工具,注意这里的版本是17,进入到libcurl目录
分辨执行命令:
//编译为静态链接库
set RTLIBCFG=static
//以下俩个分辨编译为debug,release模式
nmake /f Makefile.vc mode=static vc=17 debug=yes
nmake /f Makefile.vc mode=static vc=17 debug=no
经过一段时间,在libcurl/build目录下已经生成我们需要的库文件及相关头文件,其中红色部分为主要目录,其它目录都可以删除
打开"libcurl-vc17-x86-debug-static-ipv6-sspi-schannel",可以看到如下目录
至此,编译库文件算是完成了。
3. 测试DEMO
新建Windows Console工程,将刚才生成的"include","lib"拷贝工程源码目录中,修改源码
//在include "pch.h"之后增加
#define CURL_STATICLIB
//增加libcurl库的引用
#include "curl/curl.h"
//增加所必须库
#pragma comment (lib, "Normaliz.lib")
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Wldap32.lib")
#pragma comment (lib, "Crypt32.lib")
#pragma comment (lib, "Advapi32.lib")#pragma comment (lib, "lib/libcurl_a_debug.lib")
测试代码如下:
- int testPost(void)
- {
- CURL* curl;
- CURLcode res;
-
- /* In windows, this will init the winsock stuff */
- curl_global_init(CURL_GLOBAL_ALL);
-
- /* get a curl handle */
- curl = curl_easy_init();
- if (curl) {
- /* First set the URL that is about to receive our POST. This URL can
- just as well be a https:// URL if that is what should receive the
- data. */
- curl_easy_setopt(curl, CURLOPT_URL, "https://curl.se/libcurl/c/http-post.html");
- /* Now specify the POST data */
- //curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "name=daniel&project=curl");
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
-
- /* 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);
- }
- curl_global_cleanup();
- return 0;
- }