如何使用 LLVM 在 MacOS 上构建 ELF?

How to build ELF on MacOS using LLVM?

我正在尝试使用 LLVM(来自 Homebrew)构建 ELF 文件,但我不知道如何 link它。

我的文件:
multiboot2.h:

struct multiboot2_header_t {
// Stub
} multiboot2_header __attribute__((section(".multiboot")));

kernel.c:

#include "multiboot2.h"

void _start() {
// Stub
}

linker.ld:

ENTRY(_start)

SECTIONS
{
    .text: {
    /* link the multiboot struct here */
    . = ALIGN(8);
    KEEP(*(.multiboot))
    /* place all of your code afterwards */
    *(.text)
    }
}

我可以通过命令 clang -c -o kernel.o kernel.c --target x86_64-none-gnu 将它编译成目标文件 kernel.o 但我不知道如何 link 这个目标文件使用我的 linker 脚本。

P.S. 之前我从未使用过 LLVMlinker 直接,仅 GNU GCC 构建简单的 Linux 应用程序。

clang --target=aarch64-unknown-linux-gnu -c file.c

Clang 会发现您的目标是 Linux 并发出 ELF file.o

% file file.o
file.o: ELF 64-bit LSB relocatable, ARM aarch64, version 1 (SYSV), not stripped

然后您需要使用可以从 Homebrew 获得的 ld.lld。顺便说一句,链接描述文件对 ELF ld.lld 的支持非常好。但是,不存在对 Mach-O ld64.lld 的链接器脚本支持。