2

I know you can directly put ASM in C using ASM but I wondered is it possible to make a library in Assembly, compile it and then access functions your declared in that library from C?

So I know I should use pre written libraries but this is just for educational purposes and for fun! So for instance say I wanted to use a sys call to print out to the screen, now I wrote some assembly to do that and named the function print, I then compile this into some sort of lib file .so/.lib/.a what would I do at that point to refer to that function in that library?

Do I just write out the function and link it when compiling?

Thanks :)

Definity
  • 691
  • 2
  • 11
  • 31
  • 1
    "what would I do at that point to refer to that function in that library?" - you declare it so that the compiler can know about its types, calling convention, etc. and then link together the object code generated from the C source and the object code generated from your hand-written assembly. – The Paramagnetic Croissant Oct 18 '14 at 21:04

1 Answers1

0

Yes, you just write the function out and compile/assemble it into a .o. You can then use the .o just like a .o from a compiler. If you want to turn it into a library just use it as an input to ar and ranlib.

Simplest example using gcc on an x86:

Put this into test.s:

.globl some_func
some_func:
    ret

Compiling: cc -c test.s

This will produce a test.o file with the function some_func defined.

A more complete example of do nothing C function foo that takes no arguments (gcc x86-64):

.globl foo
.type   foo, @function
foo:
    pushq   %rbp
    movq    %rsp, %rbp
    leave
    ret
Craig S. Anderson
  • 6,966
  • 4
  • 33
  • 46
  • Definitely make sure you respect the C calling conventions. Depending on the platform, some registers might be _callee_-save! – Alex Reinking Oct 23 '14 at 02:53
  • The complete example does respect the gcc calling conventions, since it writes none of the x86 GPRs. Proof - the code was generated by gcc. I just removed some of the labels. – Craig S. Anderson Oct 23 '14 at 04:42
  • I wasn't saying that it wasn't! I was just pointing out that while this example is correct, it might not be on, say, PowerPC. OP didn't indicate which compiler he was using, nor which platform he was targeting. – Alex Reinking Oct 23 '14 at 04:56