V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
therlf
V2EX  ›  问与答

请问 LLVM 如何链接多个目标文件呢?

  •  
  •   therlf · 2022-08-15 10:44:08 +08:00 · 540 次点击
    这是一个创建于 626 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在看 LLVM 的 toturial : Kaleidoscope: Code generation to LLVM IR,里面的代码把所有东西都写到一个源文件了,而我选择将它们分为 lexer 、parser 、ast 分别写到不同的代码里,然后分别编译最后链接到一块

    这是我的编译指令

    c++ clang++ -g -O3 -I /home/therlf/LLVM/include -I ./ -I /home/therlf/LLVM_Temp/llvm/include `llvm-config --cxxflags --ldflags --system-libs --libs all` ast/CallExprAST.o ast/NumberExprAST.o ast/PrototypeAST.o ast/FunctionAST.o ast/BinaryExprAST.o ast/VariableExprAST.o lexer/lexer.o logger/logger.o parser/parser.o main.cpp -o main

    然后就出现了一系列的undefined error,截取一些如下:

    /usr/bin/ld: /tmp/main-2b71c8.o:(.data+0x0): undefined reference to llvm::DisableABIBreakingChecks /home/therlf/MyProject/tmp/ast/CallExprAST.cpp:6: undefined reference to llvm::Module::getFunction(llvm::StringRef) const' /home/therlf/LLVM/include/llvm/IR/InstrTypes.h:1112: undefined reference to llvm::Instruction::Instruction(llvm::Type*, unsigned int, llvm::Use*, unsigned int, llvm::Instruction*)' /usr/bin/ld: /home/therlf/LLVM/include/llvm/IR/InstrTypes.h:977: undefined reference to llvm::VectorType::get(llvm::Type*, llvm::ElementCount)'

    我一开始以为是 Including path 的问题,但是我编译 tutorial 那个所有东西都在一块的代码是没问题的,自己编译各个模块也是没问题的,就是在一起编译链接了才会有问题,显示很多很多"undefined error"。

    所以我认为是链接的问题,到网上搜一些博主说你必须使用lld来链接,而不是ld,但是之前 LLVM 没有 lld 的时候也是用 ld 来链接的,所以感觉使用 ld 应该也可以,而且我编译完 LLVM 后没有 lld 这个工具。

    我的操作系统是Ubuntu 20.04,LLVM 版本为10.0.0svn。 我的 Makefile 如下:

    HEADERS = $(shell find ast kaleidoscope lexer logger parser -name '*.h')
    OBJ = ${SOURCES:.cpp=.o}
    
    CC = clang++
    CFLAGS = -g -O3 -I /home/therlf/LLVM/include -I ./ -I /home/therlf/LLVM_Temp/llvm/include
    LLVMFLAGS = `llvm-config --cxxflags --ldflags --system-libs --libs all`
    
    .PHONY: main
    
    main: main.cpp ${OBJ}
        ${CC} ${CFLAGS} ${LLVMFLAGS} ${OBJ} $< -o $@
    
    clean:
        rm -r ${OBJ}
    
    %.o: %.cpp ${HEADERS}
        ${CC} ${CFLAGS} ${LLVMFLAGS} -c $< -o $@ ```
    
    
    万分感谢您的帮助!
    therlf
        1
    therlf  
    OP
       2022-08-15 12:23:05 +08:00
    最后还是通过下载 lld ,并且设置它为默认的 linker 解决了: )
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   752 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:01 · PVG 05:01 · LAX 14:01 · JFK 17:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.