LinuxでのCコードからアセンブラ関数を呼び出します

ミハイルHRS:

私は私のCプログラムから印刷機能を呼び出したいです。
アセンブラPROG:

 #test.s
.text

    .global _start
    .global print
    .type print, @function

_start:

        call print

        # and exit.

        movl    $0,%ebx         # first argument: exit code.
        movl    $1,%eax         # system call number (sys_exit).
        int     $0x80           # call kernel.

print:
    # write our string to stdout.

        movl    $len,%edx       # third argument: message length.
        movl    $msg,%ecx       # second argument: pointer to message to write.
        movl    $1,%ebx         # first argument: file handle (stdout).
        movl    $4,%eax         # system call number (sys_write).
        int     $0x80           # call kernel.

        mov $0,   %eax
        ret
.data

msg:
        .ascii  "Hello, world!\n"      # the string to print.
        len = . - msg                  # length of the string.

私は組み立て、それを使用してリンクすることができます。

$as test.s -o test.o
$ld test.o -o test

そして、私はそれをプログラムとして実行することができ、それが出力「こんにちは、世界!」しかし、私はこのようなCコードから印刷を呼び出すようにしようとしたとき:

#include <stdio.h>
extern int print();

int main(){
    int g;
    g = print();
    printf("Hello from c!, %d\n", g);

}

これは、使用してコンパイルされました:

$gcc -c main.c test

それはちょうど手段は関数が呼び出されると、文字の数を返しますが、何も印刷されないことをしていることを、「こんにちはC、13から」印刷します!

何が私が間違っているのでしょうか?

PSは、私はこのようなプログレをコンパイルしようとすると:

$as test.s -o test.o
$gcc -c main.c -o main.o
$gcc main.c test.o 

私はエラーがあります:

/usr/bin/ld: test.o: in function `_start':
(.text+0x0): multiple definition of `_start'; /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/../../../../lib/Scrt1.o:(.text+0x0): first defined here
/usr/bin/ld: test.o: relocation R_X86_64_32 against `.data' can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: final link failed: nonrepresentable section on output
collect2: error: ld returned 1 exit status
ミハイルHRS:

[OK]を、やりました!おかげclearlight

私はすべての使用をコンパイルすることができます

$as test.s -o test.o
$gcc -c main.c -o main.o
$gcc -no-pie main.c test.o 

そして、すべてはうまく動作します!

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=21814&siteId=1