GCC:如何完全禁用MCU上的堆使用情况? [英] GCC: How to disable heap usage entirely on an MCU?

查看:79
本文介绍了GCC:如何完全禁用MCU上的堆使用情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序可以在基于ARM Cortex-M的MCU上运行,并用C和C ++编写.我使用gccg++进行编译,并希望完全禁用任何堆使用情况.

I have an application that runs on an ARM Cortex-M based MCU and is written in C and C++. I use gcc and g++ to compile it and would like to completely disable any heap usage.

在MCU启动文件中,堆大小已经设置为0.除此之外,我还要禁止在代码中使用任何意外的堆.

In the MCU startup file the heap size is already set to 0. In addition to that, I would also like to disallow any accidental heap use in the code.

换句话说,当malloccallocfree函数或newnew[],使用delete[]运算符.

In other words, I would like the linker (and/or the compiler) to give me an error when the malloc, calloc, free functions or the new, new[], delete, delete[] operators are used.

到目前为止,我已经尝试过-nostdlib,这给了我类似undefined reference to _start的问题.我也尝试了-nodefaultlibs,但是当我尝试调用malloc时仍然没有抱怨.正确的方法是什么?

So far I've tried -nostdlib which gives me issues like undefined reference to _start. I also tried -nodefaultlibs but that one still does not complain when I try to call malloc. What is the right way to do this?

注意:

  • 此应用程序在裸机"上运行,没有操作系统.
  • 我还希望避免在第三方代码(特定于供应商的库,标准库,printf等)中使用任何malloc.
  • 我完全不使用不需要动态内存分配的C/C ++标准库的部分.
  • 我更喜欢编译时而不是运行时解决方案.

推荐答案

我不确定这是最好的方法,但是您可以使用ld--wrap标志(可以通过gcc使用-Wl).

I'm not sure it's the best way to go, however you can use the --wrap flag of ld (which can pass through gcc using -Wl).

想法是--wrap允许您要求ld将真实"符号重定向到您的自定义符号;例如,如果您执行--wrap=malloc,则ld将查找要调用的__wrap_malloc函数,而不是原始的`malloc.

The idea is that --wrap allows you to ask to ld to redirect the "real" symbol to your custom one; for example, if you do --wrap=malloc, then ld will look for your __wrap_malloc function to be called instead of the original `malloc.

现在,如果在没有定义__wrap_malloc 的情况下执行--wrap=malloc ,则如果没有人使用它,您将无法使用它,但是如果有人引用malloc,则会出现链接错误./p>

Now, if you do --wrap=malloc without defining __wrap_malloc you will get away with it if nobody uses it, but if anyone references malloc you'll get a linking error.

$ cat test-nomalloc.c 
#include <stdlib.h>

int main() {
#ifdef USE_MALLOC
    malloc(10);
#endif
    return 0;
}
$ gcc test-nomalloc.c -Wl,--wrap=malloc
$ gcc test-nomalloc.c -DUSE_MALLOC -Wl,--wrap=malloc
/tmp/ccIEUu9v.o: In function `main':
test-nomalloc.c:(.text+0xa): undefined reference to `__wrap_malloc'
collect2: error: ld returned 1 exit status

对于new,您可以使用名称混乱的名称_Znwm(operator new(unsigned long))和_Znam(operator new[](unsigned long)),这应该是每个new最终应使用的名称.

For new you can use the mangled names _Znwm (operator new(unsigned long)) and _Znam (operator new[](unsigned long)), which should be what every new should come down to in the end.

这篇关于GCC:如何完全禁用MCU上的堆使用情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆