諸如我輩菜鳥,對編譯器了解比較少,面對代碼中出現的陌生字眼真是茫然不知所措。今天查閱了一些資料,總算是有了一點了解,現在将些許了解記錄在案。
__attribute__這個關鍵詞是GNU編譯器中的編譯屬性,ARM編譯器也支援這個用法。__attribute__主要用于改變所聲明或定義的函數或 資料的特性,它有很多子項,用于改變作用對象的特性。比如對函數,noline将禁止進行内聯擴充、noreturn表示沒有傳回值、pure表明函數除 傳回值外,不會通過其它(如全局變量、指針)對函數外部産生任何影響。當然,__attribute__肯定有很多的用法,今天就用到了section部分,是以就隻針對這個做一些記錄。
提到section,就得說RO RI ZI了,在ARM編譯器編譯之後,代碼被劃分為不同的段,RO Section(ReadOnly)中存放代碼段和常量,RW Section(ReadWrite)中存放可讀寫靜态變量和全局變量,ZI Section(ZeroInit)是存放在RW段中初始化為0的變量。
于是本文的大體意思就清晰了,__attribute__((section("section_name"))),其作用是将作用的函數或資料放入指定名為"section_name"對應的段中。
MDK給出的幫助文檔如下,他将__attribute__的用法歸類到編譯器特性裡,以變量和函數的兩種用法做區分。
1.編譯時為變量指定段
__attribute__((section("name")))
RealView Compilation Tools for µVision Compiler Reference Guide Version 4.0
Home > Compiler-specific Features > Variable attributes > __attribute__((section("name")))
4.5.6. __attribute__((section("name")))
Normally, the ARM compiler places the objects it generates in sections like data and bss. However, you might require additional data sections or you might want a variable to appear in a special section, for example, to map to special hardware. The section attribute specifies that a variable must be placed in a particular data section. If you use the section attribute, read-only variables are placed in RO data sections, read-write variables are placed in RW data sections unless you use the zero_init attribute. In this case, the variable is placed in a ZI section.
Note
This variable attribute is a GNU compiler extension supported by the ARM compiler.
Example
/* in RO section */
const int descriptor[3] __attribute__ ((section ("descr"))) = { 1,2,3 };
/* in RW section */
long long rw[10] __attribute__ ((section ("RW")));
/* in ZI section *
long long altstack[10] __attribute__ ((section ("STACK"), zero_init));/
2.編譯時為函數指定段
__attribute__((section("name")))
RealView Compilation Tools for µVision Compiler Reference Guide Version 4.0
Home > Compiler-specific Features > Function attributes > __attribute__((section("name")))
4.3.13. __attribute__((section("name")))
The section function attribute enables you to place code in different sections of the image.
Note
This function attribute is a GNU compiler extension that is supported by the ARM compiler.
Example
In the following example, Function_Attributes_section_0 is placed into the RO section new_section rather than .text.
void Function_Attributes_section_0 (void)
__attribute__ ((section ("new_section")));
void Function_Attributes_section_0 (void)
{
static int aStatic =0;
aStatic++;
}
In the following example, section function attribute overrides the #pragma arm section setting.
#pragma arm section code="foo"
int f2()
{
return 1;
} // into the 'foo' area
__attribute__ ((section ("bar"))) int f3()
{
return 1;
} // into the 'bar' area
int f4()
{
return 1;
} // into the 'foo' area
#pragma arm section
記錄完畢,希望能夠給遇到同樣問題的朋友些許幫助。