-3

Trying to run assembly in C, but won't compile with gcc

main.c

#include <stdio.h>
#include "assem.s"
void extern testing(int * a);

int main(){
    int b = 8;
    int * a = &b;
    testing(a);
    printf("%d",*a);

}

assem.s

.globl testing

testing:
    ret 

gcc

gcc main.c assem.s -o test.exe

error

expected identifier or '(' before '.' token .globl testing
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Rambos
  • 3
  • 1
  • 9
    You don't include `assem.s` as a `#include` in _C_. remove `#include "assem.s"` – Michael Petch May 05 '17 at 03:52
  • 3
    `#include "assem.s"` statement inserts the contents of assem.s into this C code. Trying to compile `.globl testing` and obviously it is not a C code. – Nguai al May 05 '17 at 04:00

2 Answers2

2

When you do #include "assem.s" it takes the contents of the file assem.s and places it into the C at that point. The result would have the compiler trying to compile this:

#include <stdio.h>
.globl testing

testing:
    ret 

void extern testing(int * a);

int main(){
    int b = 8;
    int * a = &b;
    testing(a);
    printf("%d",*a);

}

Of course that's not what you want. The compiler attempted to compile the line .globl testing and it failed because it isn't proper C syntax and results in the error you got. All you have to do is remove #include "assem.s".

assem.s will be assembled and then linked into the executable with the command gcc main.c assem.s -o test.exe. This one GCC command is the equivalent of the following except that intermediate object files won't be generated:

gcc -c main.c -o main.o
gcc -c assem.s -o assem.o
gcc main.o assem.o -o test.exe

You assemble/compile .s and .S files in the same fashion as .c files. .s and .S files should not be used with the C #include directive. There is a misconception among some new GCC users that they should be included and not assembled/linked separately.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
-1

You should change main.c like this. Then they could work.

#include <stdio.h>
//#include "assem.s"
void extern testing(int * a);

int main(){
    int b = 8;
        int * a = &b;
    testing(a);
    printf("%d",*a);

    return 0;
}
Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20