Solve the error related to compiling llvm IR file: ld: library not found for -lzstd

Use clang++ to compile cpp programs:

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

}

Compile command:

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

LLVM IR compile time error:

(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)

Reason for the error: The llvm-config --system-libs command will add -lzstd to the compilation option, which means that the zstd library needs to be linked. zstd is an open source lossless data compression algorithm.

So there are only two possible reasons:

  1. Not installed in the system
  2. There is no path to the zstd library in LIBRARY_PATH, so the library cannot be found when linking.

For reason 1, you only need to install the zstd library:

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

# macos
homebrew install zstd

For reason 2, the solution:

# 找到库位置
(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/"

Compile again and it will be successful.

Note: It is true that other library files can also be solved using the same method. This method is not just for the zstd library.

Guess you like

Origin blog.csdn.net/weixin_43669978/article/details/132505196