0

我需要定义一个必须在每个文件中都可见的全局数组。我在头文件中声明了它,但它存储在堆中而不是堆栈中。我怎样才能把它放在堆栈中?谢谢

编辑:我正在使用 ATMEGA32 并将数组放在 RAM 的开头(地址 0x0060),而我需要将它放在末尾(地址 0x085F)

common.h

#define dimension 5
unsigned int board[dimension][dimension];

main.c

#include "common.h"
4

1 回答 1

2

您在头文件中有数组变量的定义。如果您将它包含在多个文件中,您将拥有相同全局变量的重复(或多个)定义,链接器将报告为错误。

在头文件中,您应该只有一个声明,例如

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")))将一个普通的全局变量放入此内存部分。

于 2021-12-09T18:42:43.383 回答