为什么在MIPS汇编语言中要使用".globl main"?

21
       .text
.globl main
.ent   main

我不知道.globl.ent的作用是什么。 它们的作用是什么? 我是否需要始终使用globl. main.ent main

2个回答

18
在你的情况下,.globl 是一个汇编指令,告诉汇编器 main 符号将可以从当前文件外部访问(也就是可以被其他文件引用),而 .ent 是一个调试器(伪)操作,标记了 main 的入口点。

5
任何其他ISA上的GNU GAS汇编器都是一样的,例如在x86_64 Linux上:
main.S
.text
.global _start
_start:
    /* exit syscall */
    mov $60, %rax
    mov exit_status, %rdi
    syscall

exit_status.S

.data
.global exit_status
exit_status:
    .quad 42

组装并运行:

as -o main.o main.S
as -o exit_status.o exit_status.S
ls -o main.out exit_statis.o main.o
./main.out
echo $?

提供:

42

但是如果我们删除这行代码:

.global exit_status

然后 ld 失败并显示如下信息:

main.o: In function `_start':
(.text+0xb): undefined reference to `exit_status'

因为它无法看到所需的符号exit_status,所以出现了问题。
如文档中所述,.globl.global是同义词:https://sourceware.org/binutils/docs/as/Global.html#Global,因此我只是更喜欢使用正确拼写的一个 ;-)
我们可以通过查看ELF对象文件中包含的信息来观察正在发生的事情。
对于正确的程序:
nm hello_world.o mystring.o

提供:

main.o:
0000000000000000 T _start
                 U exit_status

exit_status.o:
0000000000000000 D exit_status

对于不能通过的一个:

对于不能通过的一个:

exit_status.o:
0000000000000000 d exit_status

同时:

man nm

包含:

The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external). There are however a few lowercase symbols that are shown for special global symbols ("u", "v" and "w").

"D"
"d" The symbol is in the initialized data section.

"T"
"t" The symbol is in the text (code) section.

"U" The symbol is undefined.
在C语言中,可以使用"static"关键字来控制符号的可见性。在Ubuntu 16.04和Binutils 2.26.1中测试通过。
参考链接:What does "static" mean in C?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接