以前は別のファイルで定義された関数を宣言してから使用するべきだと思っていましたが、最近はプログラミングの経験から考え方を変えました。3つのファイルの場合、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);
}
kernel.asm
extern Print_String
[section .text]
global _start
global test_str
test_str dd 14
_start:
call Print_String
jmp $
another.asm
[section .text]
global myprint
myprint:
mov edx, [esp + 8]
mov ecx, [esp + 4]
mov ebx, 1
mov eax, 4
int 0x80
ret
コンパイル
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
結果
./final
a simple test
私の考えでは、main.cで関数を使用する場合myprint
は、extern
別のファイルで定義されているため、事前にを使用して宣言する必要myprint
がありますが、結果はまったく逆になります。main.cが上に示しているように。行を追加するextern myprint
と、エラーが発生します。ただし、その宣言がなければ、正しい結果が得られます。さらに、main.cmyprint
で関数を定義していませんが、なぜその関数を使用できるのですか?事前に宣言してはいけませんか?