Yewmisgoat Pretzeldragon Yewmisgoat Pretzeldragon - 3 months ago 23
C Question

Is there a GCC version of the NASM ORG instruction?

I'm currently making an OS, and when I tried to add C support, I ran into a bit of a problem... In assembly, each program on my OS starts with

ORG 32768
(the NASM compiler preprocessor instruction for offsetting the origin of the code), but I can't seem to find anything on a way to do this using the GCC compiler for C. So, my question is, how would one achieve this (offsetting the code's origin) in C using GCC? (and yes, I have looked it up before asking, even checked GNU's official GCC's C preprocessor documentation)

Answer

ORG and .ORG go back to the days when you wrote programs in assembly and didnt necessarily need a linker.

The gnu tools dont support it AFAIK.

start.s

.globl _start
_start:
    mov $0xA000,%rsp
    callq fun
    jmp .

fun.c

unsigned int fun ( void )
{
    return(7);
}

fun.ld

MEMORY
{
    ram : ORIGIN = 0x8000, LENGTH = 0x2000
}
SECTIONS
{
    .text : { *(.text*) } > ram
    .rodata : { *(.rodata*) } > ram
    .data : { *(.data*) } > ram
    .bss : { *(.bss*) } > ram
}

build commands

as start.s -o start.o
gcc -O2 -nostdlib -nostartfiles -ffreestanding -c fun.c -o fun.o
ld -T fun.ld start.o fun.o -o fun

which produces this program:

0000000000008000 <_start>:
    8000:   48 c7 c4 00 a0 00 00    mov    $0xa000,%rsp
    8007:   e8 04 00 00 00          callq  8010 <fun>
    800c:   eb fe                   jmp    800c <_start+0xc>
    800e:   66 90                   xchg   %ax,%ax

0000000000008010 <fun>:
    8010:   b8 07 00 00 00          mov    $0x7,%eax
    8015:   c3                      retq   

I used an entry point of 0x8000 (32768).

If by gcc you meant the gnu tools and just wanted to do assembly language then that makes it a bit simpler, you only need the binutils package not gcc. But you still need the linker and use the ORIGIN in the very simpler linker script example above where you would have used .ORG inline with the assembly.

start.s

.globl _start
_start:
    mov $0xA000,%rsp
    mov $0x7,%eax
    add $0x1,%eax
    jmp .

same linker script as above

as start.s -o start.o
ld -T fun.ld start.o -o fun

producing

0000000000008000 <_start>:
    8000:   48 c7 c4 00 a0 00 00    mov    $0xa000,%rsp
    8007:   b8 07 00 00 00          mov    $0x7,%eax
    800c:   83 c0 01                add    $0x1,%eax
    800f:   eb fe                   jmp    800f <_start+0xf>