Clang 链接器无法识别 Linux 库

问题描述

我即将能够在 Windows 上为 Linux 交叉编译二进制文件我有一个命令可以将我的代码编译为 .o 文件,但我无法将其链接生成二进制文件。现在它说它无法链接到 Linux 库的多个副本,即使我的系统上有它们的副本并将目录提供给链接器。

我使用的命令: clang -fuse-ld=lld -target x86_64-pc-linux-gnu -LD:/Toolchains/Linux/Libs -o main main.o -v

我收到的错误信息是:

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)

所有 cannot open *.o: no such file or directory 错误都是我在 Windows 机器上有副本的文件,所以我不确定从哪里开始让链接器识别我的文件。当我反向执行此操作时,让链接器识别和使用 Windows 库相对简单

任何帮助将不胜感激

解决方法

我相信 clang 正在为您正在编译的环境搜索 gcc C 运行时。您应该可以使用 --gcc-toolchain 标志为此设置搜索路径。

例如,在我的机器上运行以下命令(在 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 是我从 here 下载的 Linux 跨工具链的位置。

在 WSL2 下运行生成的 ./main 程序对我有用。

要编译 C++ 程序,请使用 clang++ 而不是 clang。其他都一样:

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