【问题标题】:Linking custom library with libcurl functions将自定义库与 libcurl 函数链接
【发布时间】:2022-01-11 20:11:30
【问题描述】:

我有一个名为“libcurlwrapper”的自定义静态库,它只是包装了 libcurl 函数的执行,以及一个调用该库函数的主应用程序。

编译库可以工作,但是在链接主应用程序时出现以下错误:

/usr/bin/ld: .//libcurlwrapper.a(curl_wrapper.o): in function `http3_demo()':
curl_wrapper.cpp:(.text+0xd): undefined reference to `curl_easy_init'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x39): undefined reference to `curl_easy_setopt'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x54): undefined reference to `curl_easy_setopt'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x60): undefined reference to `curl_easy_perform'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x73): undefined reference to `curl_easy_strerror'
/usr/bin/ld: curl_wrapper.cpp:(.text+0x9d): undefined reference to `curl_easy_cleanup'
collect2: error: ld returned 1 exit status
make: *** [Makefile:5: all] Error 1

究竟是什么导致了这些链接器错误?

想出如何摆脱它们?

感谢任何帮助!

谢谢

libcurlwrapper > curl_wrapper.h:

#pragma once

#include <curl/curl.h>

void http3_demo();

libcurlwrapper > curl_wrapper.cpp:

#include "curl_wrapper.h"

void http3_demo() {

    // Source taken from here: https://curl.se/libcurl/c/http3.html

    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();

    if(curl) {

        curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
        curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_3);

        // 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);

    }

    printf("http3_demo: endmarker");

}

libcurlwrapper > 生成文件:

CXX = g++
CXXFLAGS = -lcurl

all:
    @$(CXX) -c ./curl_wrapper.cpp $(CXXFLAGS)
    @ar -rc libcurlwrapper.a ./curl_wrapper.o

main_app > main.cpp:

#include "curl_wrapper.h"

int main() {

    http3_demo();

    return 0;

}

main_app > 生成文件:

CXX = g++
CXXFLAGS = -L ./ -lcurlwrapper

all:
    @$(CXX) main.cpp $(CXXFLAGS) -o main_app

【问题讨论】:

标签: c++ linux makefile libcurl ld


【解决方案1】:

一个静态库被编译成最终的可执行文件。静态库使用的外部函数只是引用。使用静态库的主可执行文件需要解析对静态库引用的所有外部库的引用。在这种情况下,这意味着主可执行项目需要链接到 libcurl 库。

【讨论】:

  • 感谢您的回答。问题中的代码是当前正在开发的项目的一个非常简化的版本,我已经尝试了通过将 -lcurl 添加到 CXXFLAGS 中的建议,但由于某种原因它没有任何帮助。我尝试使用上面的代码这样做,它就像一个魅力/所有 ld 错误都消失了!
  • 您是否还知道如何避免将主可执行项目链接到 libcurl?在 libcurlwrapper 库中是否有一些方法可以做到这一点? (出于封装原因)
  • 将包装器编译成动态库而不是静态库,这样就可以自包含了。
  • 有什么方法可以使静态库自包含?
  • @user17906461 不是真的,不。这就是静态库如何工作的本质。与目标文件一样,静态库中的外部引用直到链接器阶段才会解析。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
相关资源
最近更新 更多