解决编译llvm IR文件相关报错:ld: library not found for -lzstd

使用clang++编译cpp程序:

#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Verifier.h"

using namespace llvm;

int main() {
    LLVMContext context;
    Module *module = new Module("test", context);
    IRBuilder<> builder(context);


    // 创建一个函数
    llvm::Function *func = llvm::Function::Create(
        llvm::FunctionType::get(builder.getInt32Ty(), false),
        llvm::Function::ExternalLinkage,
        "main",
        module
    );

    verifyFunction(*func);

    module->dump();
    return 0;

}

编译命令:

clang++ -O3 `llvm-config --cxxflags --ldflags --system-libs --libs core` -o toy

LLVM IR 编译时报错:

(base) liushanlin@192 chapter2 % make                            
clang++ -O3 -I/Users/liushanlin/cpp_directory/llvm-project/llvm/include -I/Users/liushanlin/cpp_directory/llvm-project/build/include -std=c++17   -fno-exceptions -funwind-tables -fno-rtti -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_LIBCPP_ENABLE_HARDENED_MODE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS emit_module.cpp -L/Users/liushanlin/cpp_directory/llvm-project/build/lib -Wl,-search_paths_first -Wl,-headerpad_max_install_names -lLLVMCore -lLLVMRemarks -lLLVMBitstreamReader -lLLVMBinaryFormat -lLLVMTargetParser -lLLVMSupport -lLLVMDemangle -lm -lz -lzstd -lcurses -lxml2 -o emit_module
ld: library not found for -lzstd
clang: error: linker command failed with exit code 1 (use -v to see invocation)

报错原因:由于llvm-config --system-libs命令会使得编译选项加上-lzstd 也就是需要链接zstd这个库,zstd是一种开源无损数据压缩算法。

所以可能的原因只有两种:

  1. 系统中没有安装
  2. LIBRARY_PATH中没有zstd库所在的路径,所以在链接的时候找不到这个库

针对原因1,只需要安装zstd库即可:

# ubuntu
apt-get update
apt-get libzstd-dev

# macos
homebrew install zstd

针对原因2,解决方法:

# 找到库位置
(base) liushanlin@192 chapter2 % locate zstd
/opt/homebrew/lib/cmake/zstd
/opt/homebrew/lib/libzstd.1.5.2.dylib
/opt/homebrew/lib/libzstd.1.dylib
/opt/homebrew/lib/libzstd.a
/opt/homebrew/lib/libzstd.dylib
/opt/homebrew/lib/pkgconfig/libzstd.pc
/opt/homebrew/opt/pzstd
/opt/homebrew/opt/zstd

# 在~/.bashrc文件中将zstd库所在路径添加
vim ~/.bashrc

# 添加下面的内容
export LIBRARY_PATH="$LIBRARY_PATH:/opt/homebrew/lib/"

再次编译,即可成功。

注:确实其他库文件也可以使用相同方法解决,该方法不仅仅针对 zstd库。

猜你喜欢

转载自blog.csdn.net/weixin_43669978/article/details/132505196