2013-07-17 17 views
4

我想定義(並初始化)一些* .c文件中結構體的實例,但我希望它們收集在編譯時成爲一個連續的數組。我一直在研究使用一個自定義的部分,並使用該部分的開始和結束地址作爲結構數組的開始和結束,但我還沒有完全弄清楚細節,我寧願不寫一個自定義鏈接器腳本,如果我可以擺脫它。下面是其中沒有相當的工作我的第一次入侵的總結:在編譯時將多個文件中的變量收集到一個連續的內存塊中

// mystruct.h: 
typedef struct { int a; int b; } mystruct; 

// mycode1.c: 
#include "mystruct.h" 
mystruct instance1 = { 1, 2 } __attribute__((section(".mysection"))); 

// mycode2.c: 
#include "mystruct.h" 
mystruct instance2 = { 3, 4 } __attribute__((section(".mysection"))); 

// mystruct.c: 
extern char __mysection_start; 
extern char __mysection_end; 
void myfunc(void) { 
    mystruct * p = &__mysection_start; 
    for (; p < &__mysection_end ; p++) { 
     // do stuff using p->a and p->b 
    } 
} 
+0

我現在用的是XC16工具鏈由Microchip。 –

回答

2

爲了使用自定義部分,必須在自定義鏈接腳本定義它的起始地址。複製設備的鏈接腳本,並添加新的部分到其SECTIONS塊:

/* in custom.gld */ 
mysection 0x2000 : 
{ 
    *(mysection); 
} >data 

使對象進入這個部分,使用section屬性:

/* mycode1.c: */ 
#include "mystruct.h" 
mystruct __attribute__((section("mysection"))) instance1 = { 1, 2 }; 

/* mycode2.c: */ 
#include "mystruct.h" 
mystruct __attribute__((section("mysection"))) instance2 = { 3, 4 }; 

現在,得到的邊界您的自定義欄目,您可以使用.startof.(section_name).sizeof.(section_name)彙編運營商:

#include "mystruct.h" 

char *mysection_start; 
char *mysection_end; 
size_t mysection_size; 

int main(void) 
{ 
    asm("mov #.startof.(mysection), W12"); 
    asm("mov #.sizeof.(mysection), W13"); 
    asm("mov W12, _mysection_start"); 
    asm("mov W13, _mysection_size"); 

    mysection_end = mysection_start + mysection_size; 

    mystruct *p = (mystruct *)mysection_start; 
    for (; (char *)p < mysection_end ; p++) 
    { 
     // do stuff using p->a and p->b 
    } 
} 
+0

順便說一句,我想問你爲什麼要這樣做? – mizo

+0

我需要一個配置UI來調整屬於幾個不同模塊的參數,但我不想要求每個模塊都有一個初始化過程,該過程向配置模塊註冊其參數。所以我想,我可以在編譯時以某種方式「註冊」參數嗎? –

+1

我在鏈接器腳本中使用'__mysection_start =。;'和'__mysection_end =。'結束了定義段開始和結束符號。另外,事實證明,您可以通過將鏈接器命令行添加到鏈接器命令行來增加平臺默認鏈接器腳本。 –

相關問題