macosclangllvmelflld

How to build ELF on MacOS using LLVM?


I am trying to build ELF-file using LLVM (from Homebrew) but I can't get how to link it.

My files:
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)
    }
}

I can compile it to object file kernel.o by command clang -c -o kernel.o kernel.c --target x86_64-none-gnu but I can't get how to link this object file using my linker script.

P.S. Before I never worked with LLVM and linker directly, only GNU GCC building simple Linux apps.


Solution

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

    Clang will see that you are targeting Linux and emit an ELF file.o

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

    You'll then want to use ld.lld which you can get from Homebrew. BTW, linker script support for ELF ld.lld is quite good. However, linker script support for Mach-O ld64.lld is non-existent.