编译时数据段太大

data segment too large while compiling

本文关键字:段太大 数据 编译      更新时间:2023-10-16

在这里,我将一个位数组传递给其他函数。由于数组大小太大,因此在编译时会抛出"数据段太大"的错误。

我新编辑了代码。但是,错误:数据段太大仍然存在

这是代码:

char TxBits[]={0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,     
               0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
               0,0,0,0,0,0,0,1,0,0,1,0,1,0,1,1,0,1,1,0,1,1,1,0,
               0,0,0,1,1,0,0,0,1,0,0,1,0,0,1,1,1,1,1,1,0,1,0,1,
               0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
               0,0,0,0,0,0,0,0,0,0,0,0,0,0};
 int nTxBits = sizeof(TxBits)/sizeof(char);
void data(char *TxBits,int nTxBits, int loopcount)
{
  int i;
  for (i = 0;i < nTxBits;i++)
  {
    gpio=TxBits[i];    
    wait(loopcount);
  }
}

因此,我正在考虑将数组中的位转换为字节并传递给函数。我可以知道如何进行吗?乐于接受建议。请回复

从您的代码中,我认为您正在使用一些微控制器,所以我不确定您是否认真对待C++标签。如果是,这是一个C++式解决方案,它使用std::bitset(用于处理需要更少空间的位的专用容器(:

std::bitset<134> foo (std::string("01010101010101010101010100101010101010101010101010010101010101010101010101001010101010101010101010100101010101010101010101010100000000"));
void data(const std::bitset& bitset, int loopcount) {
  // if C++11 
  for (auto& bit : foo) {
    gpio = bit;
    wait(loopcount);
  }
  // if C++98
  // for (int i = 0; i<bitset.size(); i++) {
  //   gpio = foo[i];
  //   wait(loopcount);
  // }
}

您可能需要这个:

void data(char *TxBits, int size)  // size of the number of elements of your table
{
  int i;
  for (i = 0;i < size; i++)
  {
    gpio=TxBits[i];    
    wait(loopcount);
  }
}

调用函数

data(TxBits, sizeof(TxBits) / sizeof(TxBits[0]);

为了获取数组的元素数,我们使用sizeof(TxBits) / sizeof(TxBits[0]其中sizeof(TxBits)是数组在内存中占用的字节数,sizeof(TxBits[0]是数组中一个元素的大小。

我正在将一个位数组传递给其他函数

不,您正在传递一个字节数组,每个字节具有二进制值 00000000 或 00000001。

为了节省内存,您应该将位值存储为实际位而不是字节:

uint8_t TxBits[]=
{  0x55, // 0,1,0,1,0,1,0,1,
   0x55, // 0,1,0,1,0,1,0,1,
   0x55, // 0,1,0,1,0,1,0,1,
   0x00, // 0,0,0,0,0,0,0,0,
   0x20, // 0,0,1,0,0,0,0,0,
   ...
};
size_t nTxBits = sizeof(TxBits) / 8;

在执行算术运算时,还应避免使用 char 类型,因为它具有实现定义的符号性。

此外,如果这是一个小型微控制器系统,则应尽可能将数据分配在ROM而不是RAM中。即:const uint8_t TxBits[].

您的参数未正确声明。替换此内容:

void data(char TxBits)

通过这个

void data(char [] TxBits)

你的函数

void data(char TxBits)

应该是

void data(char *TxBits, size_t nTxBits)
{
    int i;
    for (i = 0;i < nTxBits;i++)
    {
        gpio=TxBits[i];    
        wait(loopcount);
    }
}

您可以通过以下方式调用它:

data ( TxBits, sizeof(TxBits)/sizeof(TxBits[0]) );

在这种特定情况下,您有一个char数组,您还可以编写:

data (TxBits, sizeof(TxBits));