跳到主要内容

Centos7编译logo4cxx-0.97问题记录

这个编译错误是由于在 C++98 标准下缺少必要的头文件声明导致的。以下是详细分析和解决方案:

问题分析

  1. 错误核心

    • socketoutputstream.cpp 中调用 memcpy 函数时,编译器报错 memcpy was not declared in this scope
    • 这是因为代码中没有包含 string.hcstring 头文件
  2. 深层原因

    • 旧版代码可能隐式依赖了某些被废弃的 GCC 特性
    • C++98 标准要求显式包含内存操作函数的头文件
    • 现代编译器(如 GCC 11)对标准合规性要求更严格

解决方案

方法 1:修改源代码(推荐)

  1. 编辑 socketoutputstream.cpp 文件:
    vim /opt/log4cxx-0.9.7/src/socketoutputstream.cpp
  2. 在文件开头添加头文件引用:
    #include <cstring>  // 添加这一行

方法 2:强制兼容模式

如果无法修改源代码,可以通过编译器选项绕过:

# 重新配置时添加
export CXXFLAGS="-include cstring -std=c++98 -D_GLIBCXX_USE_CXX11_ABI=0"
./configure \
--enable-shared \
--with-pic

make clean
make

方法 3:使用补丁文件

  1. 创建补丁文件 fix_memcpy.patch
    --- a/src/socketoutputstream.cpp
    +++ b/src/socketoutputstream.cpp
    @@ -1,4 +1,5 @@
    #include "log4cxx/helpers/socketoutputstream.h"
    +#include <cstring>

    using namespace log4cxx;
    using namespace log4cxx::helpers;
  2. 应用补丁:
    patch -p1 < fix_memcpy.patch

完整修复流程

# 1. 进入源码目录
cd /opt/log4cxx-0.9.7

# 2. 应用修复(任选一种方法)
# 方法1:手动修改
sed -i '1i #include <cstring>' src/socketoutputstream.cpp

# 或方法2:使用补丁
cat > fix.patch <<'EOF'
--- a/src/socketoutputstream.cpp
+++ b/src/socketoutputstream.cpp
@@ -1,4 +1,5 @@
#include "log4cxx/helpers/socketoutputstream.h"
+#include <cstring>

using namespace log4cxx;
using namespace log4cxx::helpers;
EOF
patch -p1 < fix.patch

# 3. 重新编译
make clean
make -j$(nproc)

预防性措施

对于其他可能出现的类似问题,建议在配置时添加:

export CXXFLAGS="-D_GLIBCXX_USE_CXX11_ABI=0 -std=c++98 -include cstring -include memory"
./configure --prefix=/usr/local/log4cxx

注意事项

  1. 如果项目中有多个文件使用 memcpy,可能需要全局搜索并统一添加头文件
  2. 在 CentOS 8+/Debian 12 上建议使用 devtoolset 或 GCC 降级:
    # CentOS
    yum install devtoolset-9
    scl enable devtoolset-9 bash

    # Debian
    apt install gcc-8 g++-8
    export CC=gcc-8 CXX=g++-8

这种问题在现代系统编译旧代码时很常见,核心思路是:要么让代码适应新标准,要么让编译器放宽检查标准。