【问题标题】:arm gcc const string array not placed in rodataarm gcc const字符串数组未放置在rodata中
【发布时间】:2017-09-11 05:05:31
【问题描述】:

关于 C 中的 ARM-GCC 当定义一个 const 字符串数组并直接访问它时,字符串被正确放置在 .rodata 部分中。

但是,如果我有一个结构,其中包含指向 .data 部分中的字符串数组的指针并使用 ram。如何将 myStrings 放入只读部分并保存 ram?

const char * myStrings[] = {"String1", "String2"};   //.rodata
const char * myStrings2[] = {"String3", "String4"};  //.data

typdef struct {
const char ** strings;
int a;
} mystruct_t;

const mystruct_t mystruct = {myStrings2,2};

void main()
{
    for(uint8_t i=0;i<2;i++)
    {
        printf("%s",myStrings[i]); 
        printf("%s",mystruct.strings[i]);
    }
}

编辑:提供最少的代码。

【问题讨论】:

  • 是字符串本身还是被放置在 .data 中的指针数组?
  • 这不是有效的 C 代码。阅读How to Ask 并提供minimal reproducible example!请注意,指针不是数组。
  • ...而您在 const mystruct_t = {myStrings,2}; 中缺少标识符
  • @Dmitri 你是对的!根据大小,它面对存储在数据中的指针(每个字符串 4 字节)。仍然没有必要吗?我可以避免这种情况吗?
  • 试试char const * const myStrings[] = ...。第一个 const 适用于 char (就像在您的原始行中一样),第二个适用于数组中的指针。

标签: c gcc arm


【解决方案1】:

正如@Dmitri 指出的那样,只有指向字符串的指针存储在 ram 中。这也可以通过将它们声明为常量来避免

const char * const myStrings2[] = {"String3", "String4"};

typdef struct {
    const char * const * strings;
    int a;
} mystruct_t;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    相关资源
    最近更新 更多