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

Undefined symbols when using curl in C++

我想使用 curl 通过 http 获取文件。我的环境是GCC(Mac OS X)。我创建了一个简单的 class 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)

我的共享代码class很简单:

#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;
    }
};

我做错了什么?

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

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