我正在为 Microchip pic32 微 Controller 使用 xc32 编译器。
程序内存大小(用于启动、 vector 等)为 1656 字节。
#include <plib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
//if I use const char array[] for string literal then the size of the program memory increased
//equal to the string length(only 12 bytes)
//const char array[] = "Hello World"; //program mem size(1668 0x684) bytes
//but in this case size increased 28 bytes
//const char *array = "Hello World"; //program mem size(1684 0x694) bytes
int main {
while(1);
}
为了优化目的:
哪个好(速度和大小)?
- #define STRLIT“ Hello World ”
- const char *strlit = "HELLO WORLD";
- const char arr[] = "HELLO WORLD"
最佳答案
一般MCU上的内存是这样存储的:What resides in the different memory types of a microcontroller?这意味着:
字符串文字
"HELLO WORLD"
本身很可能存储在.rodata
闪存 ROM 部分中。当您在文件范围执行
const char array[] = "Hello World";
时,array
变量应该分配在.rodata 中
。因此不需要分配字符串文字,否则将意味着冗余分配。当您执行
const char *array
时,您声明了一个指针,它不是分配在闪存中,而是在.data
RAM 部分。所以这将意味着 RAM 和闪存消耗。请注意,此指针是可读/可写的 - 您可以将其分配到其他地方,但不能更改指向的内容。要在 flash ROM 中分配指针,需要执行
const char* const array
。
至于为什么你得到“28字节”的东西,我不知道。我没有用过这部分,但做了一个简短的研究here声称它可能具有冯诺依曼特性,从 C 程序员的角度来看,即使核心是哈佛。不确定归结为什么,但这很重要,因为哈佛架构可能需要执行一些支持开销代码来访问闪存 ROM 数据,这反过来会导致可执行文件的大小稍大。想知 Prop 体情况需要拆机。
关于arrays - 为什么 const char *arr 的大小大于 const char arr[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71016218/