Home > Back-end >  stdout not working properly with linked assembly function in simple c program
stdout not working properly with linked assembly function in simple c program

Time:07-19

I am trying to learn arm assembly currently, and I've been toying with blending c and asm together. What I made was a simple program that will enter an infinite loop (written in assembly) where a string is output to the console. The problem that I've run into is that the output when I run the assembly code by itself works as expected, but when I try to access the function from inside a C program, then the output is not the same as it was originally.

sample.c

#include <stdio.h>

void loop();

int main (void){

        printf("Before loop:\n");
        loop();
        printf("After loop:\n");

}

assembly.s

.global loop

loop:
        MOV R0, #1
        LDR R1, =message
        LDR R2, =len
        MOV R7, #4
        SWI 0
        b loop

.data
message:
        .asciz "Hello from inside loop\n"

len = .-message

I compiled it as follows

as assembly.s -o assembly.o
ld assembly.o -o assembly
gcc sample.c assembly -o sample
./sample
Before loop:

^C

However when I run the asm by itself, it runs without issue. Anyone have a second to explain this to me?

    ./assembly
    Before loop:
    Hello from inside loop
    Hello from inside loop
    Hello from inside loop
    Hello from inside loop
    ^C

EDIT: for clarification, there was a long string of unicode characters after the C version of the program, that were filtered out of this post. It was not the appropriate output but there was an infinite string of some character.

CodePudding user response:

As Jester stated in their comment, the answer is that I was not compiling correctly:

You need to link the object file not the executable. So do

gcc sample.c assembly.o -o sample

Note gcc can invoke the assembler for you so can do it in one step:

gcc sample.c assembly.s -o sample
  • Related