按照一般教科書(shū)上的說(shuō)法,C語(yǔ)言中的局部變量應(yīng)該是分配在"棧"中的。而實(shí)際情況,有些出入錄,肯能更容易理解。 這一段代碼,唯一的用途,就是分配變量。 int func1(void) { volatile int father; volatile int mother; volatile int boy; volatile int girl; father = 30; mother = boy = girl = father; return father; } int func2(void) { volatile int father; volatile int mother; volatile int boy; volatile int girl; volatile int unnecessary; father = 30; mother = boy = girl = father; unnecessary = 0; return father; } int func3(void) { volatile int stone[2]; stone[0] = 30; return stone[0]; } int func4(void) { volatile int stone[2]; stone[0] = 30; if(stone[0] == 30) { volatile int father; father = 91; } else { volatile int mother; mother = 90; } return stone[0]; } int func5(void) { volatile int stone[2]; stone[0] = 30; if(stone[0] == 30) { volatile int boy[2]; boy[0] = 91; } else { volatile int girl[2]; girl[0] = 90; } return stone[0]; } int func10(int a, int b, int c, int d) { return a + b + c + d; } int func11(int a, int b, int c, int d) { volatile int father = a; volatile int mother = b; volatile int boy = c; volatile int girl = d; return father + mother + boy + girl; } typedef struct Home { int father; int mother; } THome; int func12() { THome home; home.father= 12; home.mother = 12; return home.father + home.mother; } typedef int uint32; int func13() { uint32 home = 2; home *= 2; return home; } int main(void) { func1(); func2(); func3(); func4(); func5(); func10(1,2,3,4); func11(1,2,3,4); func12(); func13(); } 通常,ADS編譯的代碼使用R13作為堆棧指針,也就是SP。 先看看剛進(jìn)入main()函數(shù)的時(shí)候,R13=0x08000000。 單步執(zhí)行一步后,R13=0x07FFFFC。減少了4字節(jié),PC入棧引起。 進(jìn)入fun1()后,R13=0x07FFFFC。沒(méi)有變化,說(shuō)明這幾個(gè)變量沒(méi)有入棧,實(shí)際上他們分別分配在R0-R3。 進(jìn)入fun2()后,R13=0x07FFFF8。比0x07FFFFC少4字節(jié),前4個(gè)仍然分配在R0-R3,第5個(gè)變量入棧。 進(jìn)入fun3()后,R13=0x07FFFF0。比0x07FFFFC少12字節(jié),除了數(shù)組入棧外,還有PC。 進(jìn)入fun4()后,R13=0x07FFFF0。跟func4()一樣,數(shù)組和PC入棧,分支中的變量放在R0中。 進(jìn)入fun5()后,R13=0x07FFFE8。比f(wàn)un4()少8字節(jié),說(shuō)明分支中的數(shù)組也入棧了。 進(jìn)入fun10()后,R13=0x07FFFFC。4個(gè)函數(shù)形參也是分配在R0-R3。 進(jìn)入fun11()后,R13=0x07FFFEC。比0x07FFFFC少16字節(jié),4個(gè)形參仍然分配在R0-R3,另外4個(gè)變量入棧。 進(jìn)入fun12()后,R13=0x07FFFF0。跟func4()一樣,結(jié)構(gòu)體變量也是入棧的。 進(jìn)入fun13()后,R13=0x07FFFFC。沒(méi)有變化,char、int這些變量即使經(jīng)過(guò)typedef,其處理方法仍然不變。 |