llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.06k stars 11.59k forks source link

Linking object files from LLVM API C++ code #62643

Open Gibson85 opened 1 year ago

Gibson85 commented 1 year ago

Hi, until now I am linking an object file DemoApplication.o generated from LLVM IR code with e.g. the following console call:

clang++ -g -O3 DemoApplication.o
llvm-config --cxxflags --ldflags --system-libs --libs all -o DemoApplication

But I would like to do this by the LLVM API now, but can't figure out how. Can you give me a hint what to do? Which classes should I use?

Leporacanthicus commented 1 year ago

I'm not even sure that LLVM has the tools to do that. It supports linking multiple LLVM-IR (bitcode) files together, which is also the basis for LTO and LLD, but I think it still relies on binutls ld to actually perform the linking (or link.exe in case of Windows). I may be wrong - no doubt someone will correct me, because the best way to get a response on something on the internet is to post something that is wrong... :)

You could use -v on your clang++ command, and see what link-command it does. And depending on what your LLVM-IR contains, you may not need all of the C++ libraries... All that clang does is call ld with the arguments it figured based on the command-line you gave.

In my compiler, I'm basically just calling clang (or gcc) to link the exectuable. See https://github.com/Leporacanthicus/lacsap/blob/master/binary.cpp#L126 (I'm not proud of that code, but it does a good enough job that I haven't found a reason yet to rewrite it).

Clearly, there are tools in LLVM to do this, but it gets rather complicated - in particular locating libraries is a big messy - even more so if you support also building with gcc.

dwblaikie commented 1 year ago

There have been various discussions/efforts to make lld more usable as a library for use cases like this - it's sort of supported? https://groups.google.com/g/llvm-dev/c/K30vI0AU9vg?pli=1 might have some slightly outdated context.

Perhaps @MaskRay has more recent posts/context/documentation about this.