mingw 编译 curl
下载curl 源码
https://github.com/curl/curl
我使用8.3版
CMake-gui 配置
源码路径:D:/workspace/CPP/curl-8.3.0
生成路径: D:/workspace/CPP/curl-8.3.0/mingw-build
点击 Configure ,弹窗配置,选择 MinGW Makefiles
选择 Specify native compilers
点击 next 配置编译器路径
C 编译器 : C:/Qt/Qt5.12.12/Tools/mingw730_64/bin/gcc.exe
C++ 编译器 : C:/Qt/Qt5.12.12/Tools/mingw730_64/bin/g++.exe
点击 Finish
报错 : CMake Error: CMake was unable to find a build program corresponding to “MinGW Makefiles”. CMAKE_MAKE_PROGRAM is not set.
勾选 Advanced 配置 CMAKE_MAKE_PROGRAM
变量 C:/Qt/Qt5.12.12/Tools/mingw730_64/bin/mingw32-make.exe
生成 Makefiles
点击Generate 生成
编译
打开 Qt mingw 命令行窗口
切换到 生成 Makefiles的路径 D:\workspace\CPP\curl-8.3.0\mingw-build
cd /d D:\workspace\CPP\curl-8.3.0\mingw-build
输入命令编译:
mingw32-make -f Makefile
生成库 libcurl.dll.a libcurl.dll:
在Qt 工程中使用
新建Qt 工程
在源码目录新建 libcurl :
curl 源码 include 目录 copy到 libcurl
libcurl/include/curl
lib/libcurl.dll
lib/libcurl.dll.a
pro中添加
LIBS += -L$$PWD/libcurl/lib/ -llibcurl.dll
INCLUDEPATH += $$PWD/libcurl/include
DEPENDPATH += $$PWD/libcurl/include
main.cpp 中替换 http://example.com/login 为需要测试的url
#include <iostream>
#include <curl/curl.h>
#include <string>
size_t WriteCallback(void *contents, size_t size, size_t nmemb, std::string *userp) {userp->append((char*)contents, size * nmemb);return size * nmemb;
}
std::string postData(const std::string& username, const std::string& password) {CURL *curl;CURLcode res;std::string buffer;curl_global_init(CURL_GLOBAL_DEFAULT);curl = curl_easy_init();if(curl) {//http://example.com/logincurl_easy_setopt(curl, CURLOPT_URL, "http://example.com/login"); // Replace with your URL// Set the POST datacurl_easy_setopt(curl, CURLOPT_POSTFIELDS, "username=" + username + "&password=" + password);// Activate writing the received data to a buffer instead of sending it to stdoutcurl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);// Perform the POST requestres = curl_easy_perform(curl);// Check for errorsif(res != CURLE_OK) {std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;}// Always cleanupcurl_easy_cleanup(curl);}// Deinitialize cURL stuffcurl_global_cleanup();return buffer;
}
int main() {std::string username = "myusername";std::string password = "mypassword";std::string response = postData(username, password);std::cout << response << std::endl;return 0;
}