Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when linking *.a and *.o files at llvm

Tags:

c

gcc

llvm

clang

I have two static library files (.a) and one bitecode file (.bc) ,which created with an opt pass.In this bitecode file i have added my own code and in this code i need to call a function which is declared in the static libraries. I 've noticed that the llvm-ld tool no longer exists for clang newer versions so i tried two different ways to link these three files (two libraries and one bitecode file):

1. try to link with gcc :

create with llc the object file of file.bc

$llc -filetype=obj file.bc -o file.o

link object and libs with gcc

$gcc -I  lib1.a lib2.a -O3 file.o -o file

these commands give me this error:

file.o: In function `main':
file.bc:(.text+0xc0): undefined reference to `function_in_lib'
collect2: error: ld returned 1 exit status

(function_in_lib is the function that i need to call from lib and compilers can't find this function)

2. the second way is with ld command

create with llc the object file of file.bc

 $llc -filetype=obj file.bc -o file.o

link object and libs with ld

$ld -o linked lib1.a lib2.a file.o -lc

these commands give me this error:

ld: warning: cannot find entry symbol _start; defaulting to 00000000004002b0
new.o: In function `main':
new.bc:(.text+0xc0): undefined reference to `function_in_lib'

i tried to change the order of arguments but i have more errors when i did it.I think that the fault become from the linking,any idea?

like image 428
rtroulak Avatar asked Nov 16 '25 02:11

rtroulak


1 Answers

The reason you're getting undefined references is because you're linking your libraries in the wrong way. A linker works in an incremental order - it looks at the first file you provided and gathers a list of things that file references but can't be found. Then the linker moves onto the next library and does the same thing, but also looks for opportunities to fix the undefined references from the previous libraries.

The reason that ld can't find function_in_lib is because it links file.o after the libraries and therefore doesn't get a chance to fill in the references that file.o requires. If you're looking for more specifics about linking and why you're running into this problem, this is a pretty good introduction.

If you just want to fix your problem, move the library files to after file.o in your command, i.e.

ld -o linked file.o lib1.a lib2.a -lc
like image 54
Matt Habel Avatar answered Nov 17 '25 16:11

Matt Habel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!