1

I wrote some c header and I want to use it in assembly code. How can I do that? How to compile them?

example:

somefunc.h:

// somefunc.h

int int_func(){
// some code here
}

float float_func(){
// some code here

}

main_assembly_code.h:

section .text
    global _start

_start:
    call int_func
    call float_func

    mov eax,1
    int 80h

I am using gcc for c, nasm for assembly and I am using linux.

  • @Elzaidir I don't want to use inline assembly – yercekimi31 Mar 27 '23 at 19:35
  • 3
    @Elzaidir: [That tutorial](https://www.codeinsideout.com/blog/stm32/assembly/) is full of unsafe uses of inline asm, like writing registers without declaring a clobber. I wouldn't recommend anyone learn from those examples. Even by the end of the tutorial, it still hasn't introduced the necessity of telling the compiler what registers your `asm` statement modifies, so it's very bad, hard to debug undefined behaviour. As well as inefficient stuff like `mov r0, %0` vs just using the value in the register the compiler picked. Also, it's for ARM. And GNU inline asm for x86 uses GAS, not NASM – Peter Cordes Mar 27 '23 at 19:41
  • the code in your question should already work, but you picked weird file names. You're writing your own `_start` so you just have to tell GCC not to link its own CRT startup code, like `nasm -felf32 start.asm` && `gcc -m32 -no-pie -nostartfiles foo.c start.o`. As long as you dynamically link your program with libc, or none of the C functions rely on glibc being initialized (e.g. stdio). It's weird to put asm code in a `.h`; you can't `#include` it into a C source file, so I assumed a more sensible name `start.asm` for the file that defines `_start`. – Peter Cordes Mar 27 '23 at 19:48
  • Somewhat related: [Assembling 32-bit binaries on a 64-bit system (GNU toolchain)](https://stackoverflow.com/q/36861903) re: building and linking code that defines its own `_start` with GAS or NASM. On entry to `_start`, the stack pointer (ESP) will be aligned by 16, ready to call a C function according to the i386 System V ABI. – Peter Cordes Mar 27 '23 at 19:50
  • 1
    Why are you putting code in `.h` files? Header files should only contain declarations, function definitions should be in `.c` files for C, and `.s` files for assembly. You compile them both to `.o` object files and link them. – Barmar Mar 27 '23 at 19:52
  • 1
    Oh, you would need `extern int_func` / `extern float_func` in your NASM source. Unlike GAS, undefined symbols are not assumed extern by default. You're writing the asm by hand to call them, so there's no way to tell NASM about their prototype, just the asm symbol name. – Peter Cordes Mar 27 '23 at 19:52

0 Answers0