說明一下,nm顯示的資料中
U:表示undefined symbol
T:表示symbol在Text section中
尋找main
123
$ nm -A /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/4.6/crtbegin.o /usr/lib/gcc/x86_64-linux-gnu/4.6/crtend.o /usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crtn.o 2> /dev/null |grep main
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: U __libc_start_main
/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: U main
$ strace ./hello
execve("./hello", ["./hello"], [/* 39 vars */]) = 0
...
write(1, "Hello world\n", 12Hello world
...
exit_group(1)
可以看到事實上printf使用write system call去讓OS印字串到螢幕上。而為什麼不直接用write(1, "Hello world\n", strlen("Hello world\n"));呢?看TLPI(書)有提到主要原因是system call有代價的,而libc實作了buffer減少system call呼叫的次數。有興趣的可以使用man setvbuf看看buffer的設定方式。
return 0;可以看下面的程式碼
return_status.c
12345678910111213141516171819202122
/* This demos return status */#include <stdio.h>#include <stdlib.h>intmain(intargc,char**argv){intrval=0;if(argc!=2){printf("usage: %s return_status_number(0~255)\n",argv[0]);printf("Then observe return status in $?\n");printf("ex: $ %s 121; echo $?\n",argv[0]);return2;}/* Convert return status to 0~255*/rval=atoi(argv[1]);rval=rval%255;returnrval;}