stian
stian

Reputation: 1987

gcc compilation and assemblying

I am trying to create an executable with gcc. I have two files virtualstack.c (which consists of the C-code below) and stack.s which consists of the intel x86 assembly code written in AT&T syntax (seen below the C-code). My command line command is gcc -c virtualstack.c -s stack.s, but I get two errors (line 3 in stack.s) - missing symbol name in directive and no such instruction _stack_create. I thought I have correctly declared functions from C in assembly prefixed with a underscore (_). I would be very grateful for any comments.

C code:

#include <stdio.h>
#include <stdlib.h>

extern void stack_create(void);

int main(void)
{
stack_create();

return 0;
}

Assembly code:

.global _stack_create
    .type, @function

_stack_create
pushl   %ebp
movl    $5, %esp
movl    %esp, ebp
movl    $21, %edx
pushl   %edx

Upvotes: 1

Views: 278

Answers (1)

Konstantin Vladimirov
Konstantin Vladimirov

Reputation: 7009

I will try to explain you method how to investigate such cases.

1) It is always good idea to make compiler work for you. So lets start with code (lets call it assemble.c):

    #include <stdio.h>
    #include <stdlib.h>

    /* stub stuff */
    void __attribute__ ((noinline))
    stack_create(void) { }

    int
    main(void)
    {
      stack_create();
      return 0;
    }

Now compile it to assembler with gcc -S -g0 assemble.c. stack_create function was assembled to (your results may differ, so please follow my instructions by yourself):

  .text
  .globl  stack_create
  .type stack_create, @function
stack_create:
  pushq %rbp
  movq  %rsp, %rbp
  popq  %rbp
  ret
  .size stack_create, .-stack_create

2) Now all you need is to take this template and fill it with your stuff:

  .text
  .globl  stack_create
  .type stack_create, @function
stack_create:
  pushq %rbp
  movq  %rsp, %rbp

  ;; Go and put your favorite stuff here!
  pushl   %ebp
  movl    $5, %esp
  movl    %esp, ebp
  movl    $21, %edx
  pushl   %edx
  ... etc ...

  popq  %rbp
  ret
  .size stack_create, .-stack_create

And of course make it separate .s file, say stack.s.

3) Now lets compile alltogether. Remove stub stuff from assemble.c and compile everything as:

gcc assemble.c stack.s

I got no errors. I believe you will get no errors too.

The main lesson: don't ever try to write in assembler in details like sections, function labels, etc. Compiler better knows how to do it. Use his knowledge instead.

Upvotes: 2

Related Questions