Clang linker does not recognise Linux libraries

2.8k Views Asked by At

I am close to being able to cross compile binaries for Linux on Windows. I have got a command that will compile my code to a .o file, but I am unable to get it to link to produce the binary. Right now it is saying that it can't link to several copies of Linux libraries even though I have a copy of them on my system and have given the directory to the the linker.

The commands I used: clang -fuse-ld=lld -target x86_64-pc-linux-gnu -LD:/Toolchains/Linux/Libs -o main main.o -v

The error message I am getting is:

InstalledDir: C:\Program Files\LLVM\bin
 "C:\\Program Files\\LLVM\\bin\\ld.lld" --eh-frame-hdr -m elf_x86_64 -dynamic-linker /lib64/ld-linux-x86-64.so.2 -o main crt1.o crti.o crtbegin.o -LD:/Toolchains/Linux/Libs "-LC:\\Program Files\\LLVM\\bin/../lib" main.o -lgcc --as-needed -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed crtend.o crtn.o
ld.lld: error: cannot open crt1.o: no such file or directory
ld.lld: error: cannot open crti.o: no such file or directory
ld.lld: error: cannot open crtbegin.o: no such file or directory
ld.lld: error: unable to find library -lgcc
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: unable to find library -lc
ld.lld: error: unable to find library -lgcc
ld.lld: error: unable to find library -lgcc_s
ld.lld: error: cannot open crtend.o: no such file or directory
ld.lld: error: cannot open crtn.o: no such file or directory
clang: error: linker command failed with exit code 1 (use -v to see invocation)

All of the cannot open *.o: no such file or directory errors are files that I have a copy of on my Windows machine so I am unsure where to go from here to get the linker to recognise my files. When I did this in reverse it was relatively simple to get the linker to recognise and use the Windows libraries

Any help will be appreciated

1

There are 1 best solutions below

3
On BEST ANSWER

I believe clang is searching for the gcc C runtime for the environment you are compiling for. You should be able to set the search path for this with the --gcc-toolchain flag.

For example, running the following command works on my machine (in Powershell):

clang --gcc-toolchain=$TOOLCHAIN --sysroot=$TOOLCHAIN\x86_64-linux-gnu\sysroot -fuse-ld=lld -target x86_64-linux-gnu -o main main.c

$TOOLCHAIN is the location of the Linux cross-toolchain I downloaded from here.

Running the resulting ./main program under WSL2 works for me.

To compile a C++ program, use clang++ instead of clang. Everything else is the same:

clang++ --gcc-toolchain=$TOOLCHAIN --sysroot=$TOOLCHAIN\x86_64-linux-gnu\sysroot  -fuse-ld=lld -target x86_64-linux-gnu -o main main.cpp