如何正确安装libcurl并将其链接到c ++程序?

Bea*_*180 5 c++ libcurl

我一直试图让一个c ++程序使用libcurl而无法搞清楚.在使用C++进行开发时,我通常使用visual studio,但是这个项目使用vi和一个使用VI和g ++的centos机器的ssh会话.我已经运行yum install curl,yum install libcurl,yuminstall curl-devel和yum install libcurl-devel仍然无法获取程序进行编译.

关于API的文档非常好,我可以找到有关如何使用libcurl一旦正确安装但是安装它的信息被证明是痛苦的.

代码是:

#include<iostream>
#include<string>
#include<curl/curl.h>
using namespace std;


string data; //will hold the urls contents

size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up)
{ //callback must have this declaration
    //buf is a pointer to the data that curl has for us
    //size*nmemb is the size of the buffer

    for (int c = 0; c<size*nmemb; c++)
    {
        data.push_back(buf[c]);
    }
    return size*nmemb; //tell curl how many bytes we handled
}

int main(void) {

 CURL* curl;

    curl_global_init(CURL_GLOBAL_ALL);
    curl=curl_easy_init();

    curl_easy_setopt(curl, CURLOPT_URL, "https://domain.com");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeCallback);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_USERPWD, "username:password");

    curl_easy_perform(curl);

    cout << endl << data << endl;
    cin.get();

    curl_easy_cleanup(curl);
    curl_global_cleanup();


    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我尝试编译时收到以下错误:

/tmp/ccfeybih.o: In function `main':
helloworld.cpp:(.text+0x72): undefined reference to `curl_global_init'
helloworld.cpp:(.text+0x77): undefined reference to `curl_easy_init'
helloworld.cpp:(.text+0x96): undefined reference to `curl_easy_setopt'
helloworld.cpp:(.text+0xb1): undefined reference to `curl_easy_setopt'
helloworld.cpp:(.text+0xcc): undefined reference to `curl_easy_setopt'
helloworld.cpp:(.text+0xe7): undefined reference to `curl_easy_setopt'
helloworld.cpp:(.text+0xf3): undefined reference to `curl_easy_perform'
helloworld.cpp:(.text+0x132): undefined reference to `curl_easy_cleanup'
helloworld.cpp:(.text+0x137): undefined reference to `curl_global_cleanup'
collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我找不到从这里去的地方.

A. *_* K. 6

您获得的错误是链接器错误.链接器无法找到curl库.您需要指定链接器在链接时搜索适当库的路径.

在这种情况下(如果您在标准的lib目录中安装了lib curl,例如/ usr/lib,r/usr/local/lib),则以下内容应该有效:

g ++ you_file_name.cpp -lcurl

否则,您必须指定可以找到库的目录的路径.例如:

g ++ -L/curl/lib/dir -lcurl you_file_name.cpp.

当有多个库链接时,这些事情变得复杂,因此最好使用诸如CMake之类的构建系统来协助管理包含目录/库路径和其他各种事物.