Why do we use .globl main in MIPS assembly language?
It is going to be the same in any other ISA on the GNU GAS assembler, e.g. on 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
Assemble and run:
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 $?
gives:
42
But if we remove the line:
.global exit_status
then ld
fails with:
main.o: In function `_start':
(.text+0xb): undefined reference to `exit_status'
because it cannot see the symbol exit_status
that it needs.
.globl
and .global
are synonyms as mentioned in the documentation: https://sourceware.org/binutils/docs/as/Global.html#Global so I just prefer to use the one with the correct spelling ;-)
We can observe what is going on by looking into the information contained in the ELF object files.
For the correct program:
nm hello_world.o mystring.o
gives:
main.o:
0000000000000000 T _start
U exit_status
exit_status.o:
0000000000000000 D exit_status
and for the failing one:
exit_status.o:
0000000000000000 d exit_status
And:
man nm
contains:
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.
On the C level, you can control symbol visibility with the static
keyword: What does "static" mean in C?
Tested in Ubuntu 16.04, Binutils 2.26.1.
In your case, .globl
is an assembler directive that tells the assembler that the main
symbol will be accessible from outside the current file (that is, it can be referenced from other files), and .ent
is a debugger (pseudo) operation that marks the entry of main
.