我需要定義一個全域陣列,它必須在每個檔案中都可見。我在頭檔案中宣告了它,但它存盤在堆中而不是堆疊中。我怎樣才能把它放在堆疊中?謝謝
編輯:我使用的是 ATMEGA32,陣列放在 RAM 的開頭(地址 0x0060),而我需要把它放在末尾(地址 0x085F)
common.h
#define dimension 5
unsigned int board[dimension][dimension];
main.c
#include "common.h"
uj5u.com熱心網友回復:
您在頭檔案中有陣列變數的定義。如果您將它包含在多個檔案中,您將有相同全域變數的重復(或多個)定義,聯結器將報告為錯誤。
在頭檔案中,您應該有一個宣告,例如
extern unsigned int board[dimension][dimension];
并且在檔案范圍內恰好是一個 C 檔案中的定義,即不在函式中。例如,您可以在main.c
unsigned int board[dimension][dimension];
如果您想從多個 .c 檔案訪問變數,則必須采用這種方式。
要將這個變數放在堆疊上,它必須在一個函式內,例如 in main(),但這樣你就不能將它用作全域變數。您可以將指標變數用作全域變數,并main()使用陣列地址對其進行初始化。這有一個缺點,即使用指標的函式無法從變數本身確定兩個陣列維度。當然,他們可以使用前處理器符號。
例子:
common.h
#ifndef COMMON_H
#define COMMON_H
#define dimension 5
extern unsigned int (*board)[dimension];
#endif // COMMON_H
main.c
#include "common.h"
#include "other.h"
unsigned int (*board)[dimension];
int main(void)
{
unsigned int the_board[dimension][dimension] = {{ 0 }};
board = the_board;
printf("board[1][2] = %d\n", board[1][2]);
some_function();
printf("board[1][2] = %d\n", board[1][2]);
return 0;
}
other.h
#ifndef OTHER_H
#define OTHER_H
void some_function(void);
#endif // OTHER_H
other.c
#include "common.h"
#include "other.h"
void some_function(void)
{
board[1][2] = 3;
}
如果您想讓變數位于特定地址或特定地址范圍(但不在堆疊上),您可以使用(特定于聯結器的)鏈接描述檔案在特定地址范圍內定義記憶體部分,并使用(特定于編譯器的) )#pragma section("name")或者__attribute__((section("name")))將一個普通的全域變數放入這個記憶體部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/381530.html
上一篇:8086基本數學運算式
下一篇:如何在C程式中嵌入bin檔案
