在C ++中使用curl时未定义的符号

时间:2015-01-11 12:05:16

标签: c++ gcc curl

我想使用curl通过http获取文件。我的环境是GCC(Mac OS X)。我已经创建了一个简单的类Shared来使用它像这样:

#include "Shared.h"
...
std::string str = Shared::getHTTPFile( "http://google.com" );

当我尝试使用以下命令编译它时:

g++ -o test -l curl test.cpp

我收到错误消息:

Undefined symbols for architecture x86_64:
"Shared::curlBuffer", referenced from:
 Shared::getHTTPFile(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in test-a10048.o
 Shared::writer(char*, unsigned long, unsigned long, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >*) in test-a10048.o
"Shared::errorBuffer", referenced from:
 Shared::getHTTPFile(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) in test-a10048.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我的共享类代码很简单:

#include <string>
#include <stdio.h>
#include <curl/curl.h>

class Shared {

public:
    static char errorBuffer[ CURL_ERROR_SIZE ];
    static std::string curlBuffer;
    static int writer( char *data, size_t size, size_t nmemb, std::string *buffer ) {
        curlBuffer.append( data, size * nmemb );
        int result = size * nmemb;
        return result;
    }

    static std::string getHTTPFile( std::string url ) {
        CURL *curl = curl_easy_init();
        CURLcode result;
        if (curl) {
            curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
            curl_easy_setopt(curl, CURLOPT_URL, "http://google.com" );
            curl_easy_setopt(curl, CURLOPT_HEADER, 1);
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer );
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &curlBuffer );
            result = curl_easy_perform( curl );
        }
        curl_easy_cleanup(curl);
        return 0;
    }
};

我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

g++ -o test -l curl test.cpp

看起来你只编译“test.cpp”。您还应该编译“Shared.cpp”。此外,它应该是“-lcurl”,而不是“-l curl”