【问题标题】:Log4cpp compile errorLog4cpp 编译错误
【发布时间】:2025-12-20 05:25:16
【问题描述】:

我有以下无法编译的代码。

#include <stdio.h>
#include <log4cpp/Category.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/SimpleLayout.hh>

#define LOGFILE "./test.log"

int main()
{
    /*Setting up Appender, layout and Category*/
    log4cpp::Appender *appender = new log4cpp::FileAppender("FileAppender",LOGFILE);
    log4cpp::Layout *layout = new log4cpp::SimpleLayout();
    log4cpp::Category& category = log4cpp::Category::getInstance("Category");

    appender->setLayout(layout);
    category.setAppender(appender);
    category.setPriority(log4cpp::Priority::INFO);

    /*The actual logging*/
    category.info("This is for tracing the flow");
    category.notice("This is to notify certain events");
    category.warn("This is to generate certain warnings");
}

$ g++ -I/usr/local/include/log4cpp -L/usr/local/lib/ -llog4cpp -lpthread log.cc

这编译。但后来我收到以下错误。

./a.out: error while loading shared libraries: liblog4cpp.so.4: cannot open shared object file: No such file or directory

我确实在 /usr/local/lib 文件夹中看到了 liblog4cpp.so.4。 我该如何解决这个问题?

【问题讨论】:

    标签: c++ logging log4cxx


    【解决方案1】:

    如果您从非标准位置链接,加载程序将找不到库。您有多种选择:

    1. 根据具体情况通知:LD_LIBRARY_PATH=/usr/local/lib ./aout

    2. 将路径硬编码到可执行文件中:将-Wl,-r,/usr/local/lib 添加到链接器命令中。

    3. 摆弄环境(我想你只是export LD_LIBRARY_PATH)。

    (如果您让它在非标准位置找到您的库,则适当的构建环境(例如cmake)通常会自动添加来自 (2) 的链接器选项。)

    如果您遇到加载问题,请务必检查 ldd ./a.out 以检查缺少哪些库。

    【讨论】:

      【解决方案2】:

      我在使用不同的程序时遇到了类似的错误。

      但是将这一行添加到主目录中的 .bashrc 文件中解决了它。 (通过重新登录激活并持续存在)

      export LD_LIBRARY_PATH=path/to/log4cpp/lib:$LD_LIBRARY_PATH
      

      【讨论】: