Sea*_*ene 2 c assembly gcc compilation nasm
我以前认为我们应该声明一个在使用它之前在另一个文件中定义的函数,但是最近由于编程经验我改变了我的思维方式.对于三个文件,C和ASM:
main.c中
extern test_str;
/*extern myprint*/ --> If I add the line, gcc will report an error: called object ‘myprint’ is not a function
void Print_String() {
myprint("a simple test", test_str);
}
Run Code Online (Sandbox Code Playgroud)
kernel.asm
extern Print_String
[section .text]
global _start
global test_str
test_str dd 14
_start:
call Print_String
jmp $
Run Code Online (Sandbox Code Playgroud)
another.asm
[section .text]
global myprint
myprint:
mov edx, [esp + 8]
mov ecx, [esp + 4]
mov ebx, 1
mov eax, 4
int 0x80
ret
Run Code Online (Sandbox Code Playgroud)
编
nasm -f elf another.asm -o another.o
gcc -c -g main.c -o main.o
nasm -f elf kernel.asm -o kernel.o
ld -o final main.o kernel.o another.o
Run Code Online (Sandbox Code Playgroud)
结果
./final
a simple test
Run Code Online (Sandbox Code Playgroud)
在我看来,如果我想myprint在main.c中使用该函数,我应该extern事先声明它,因为myprint 在另一个文件中定义,但结果正好相反.就像上面的main.c所示.如果我添加该行extern myprint,我将收到错误.但是,如果没有这个声明,我会得到正确的结果.更重要的是,我没有myprint在main.c中定义函数,为什么我可以使用该函数?我不应该事先申报吗?
当您调用没有原型的函数时,编译器会对该函数的参数做出一些假设和猜测.所以你应该声明它,但声明它是一个函数:
void myprint(const char *, const char *); /* Or whatever. */
Run Code Online (Sandbox Code Playgroud)