c++compiler-constructionllvmllvm-c++-apilld

Are there any C++ APIs for lld?


Currently I am implementing a compiler for my programming language. So my compiler compiles source files to .o object files, and since I want my programming language to have access to C functions like printf, I need link the .o file to libc.

To be clear, using g++ or ld in commandline as the linker works perfectly, but I want to invoke LLVM linker (lld) using C++. However, after searching through lld's documentation, I didn't find anything about its C++ API.

For anyone experienced in making a compiler using LLVM, is there a C++ API for lld? If yes, then how can I use the API or where is its documentation?

I don't want to use things like system() to call lld


Solution

  • In order to do this, you must use the llvm c++ api

    First, create your main file:

    #include <lld/Common/Driver.h>
    
    int main() {
        std::vector<const char *> args;
    
        // Equivalent to calling lld from the command line
        args.push_back("ld64.lld");
        args.push_back("-dynamic");
        args.push_back("-arch");
        args.push_back("x86_64");
        args.push_back("-platform_version");
        args.push_back("macos");
        args.push_back("11.0.0");
        args.push_back("11.0.0");
        args.push_back("-syslibroot");
        args.push_back("/Library/Developer/CommandLineTools/SDKs/MacOSX11.sdk");
        args.push_back("-lSystem");
        args.push_back("/usr/local/Cellar/llvm/15.0.5/lib/clang/15.0.5/lib/darwin/libclang_rt.osx.a");
        args.push_back("test.o");
    
        // Replace macho with elf, mingw, wasm, or coff depending on your target system
        lld::macho::link(args, llvm::outs(), llvm::errs(), false, false);
        return 0;
    }
    

    Next, compile using:

    clang++ <insert c++ file name> `llvm-config --cxxflags --ldflags --system-libs --libs core` -llldMACHO -llldCOFF -llldELF -llldCommon -llldMinGW -llldWasm -lxar
    

    If you want to see what command and flags you need for lld on your system, one way you could do that is by running clang on a c file and add -v to see the separate commands.