打印
[STM32F4]

【转】 STM32 GCC 使用 USB 库出现”undefined reference to _sbrk”问...

[复制链接]
1167|1
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
焚琴煮鹤|  楼主 | 2016-11-6 22:00 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
问题原因
​出现该问题的主要原因在于 USB 库中使用了 malloc() 和 free() 函数。在“usbd_conf.h”文件中有类似如下内容:
/* Memory management macros */   #define USBD_malloc               malloc#define USBD_free                 free

    12
  • 3

    12
  • 3
这两个函数需要使用“target specific functions” ,另外,如 printf()、scanf() 等函数都要用到“target specific functions”。
问题解决
当遇到类似问题,你可以:
  • Provide real implementations for the functions. See the syscalls.c files.
  • Use a different library.
如果使用了实时操作系统,那么还可以将malloc和free等替换成实时系统提供的函数(等同于“Use a different library”)。
我使用了FreeRTOS,该 RTOS 提供了 pvPortMalloc() 和 vPortFree() 用于替代 malloc() 和 free() 。但是,在 USB 驱动程序中无法直接使用这两个内存管理函数,因为它们内部调用了 vTaskSuspendAll() 和 xTaskResumeAll() 来挂起和恢复任务,而任务挂起和恢复函数在中断中是无法使用的。USB 驱动程序恰恰是在中断中调用的 USBD_malloc() 和 USBD_free()。因此,需要使用中断服务版本的内存管理程序或者使用内存池才真正可行。中断服务版本的内存分配/释放算法需要被 portDISABLE_INTERRUPTS()/portENABLE_INTERRUPTS() 对包围起来。具体可以参考http://www.freertos.org/FreeRTOS ... _ISR_ffdab88aj.html中的讨论。
注:非常建议使用实时系统提供的内存管理函数,因为使用标准的 malloc() 与 free() 库函数,必须承担以下若干问题:
- 这两个函数在小型嵌入式系统中可能不可用。
- 这两个函数的具体实现可能会相对较大,会占用较多宝贵的代码空间。
- 这两个函数通常不具备线程安全特性。
- 这两个函数具有不确定性。每次调用时的时间开销都可能不同。
- 这两个函数会产生内存碎片。
- 这两个函数会使得链接器配置得复杂。
沙发
焚琴煮鹤|  楼主 | 2016-11-6 22:03 | 只看该作者
SysCalls.cpp参考文件
Add this file to your project (e.g. syscalls.cpp) and paste the following code into it:
#include <stdio.h>#include <sys/stat.h>#include <stm32f10x_usart.h>extern "C" {    int _fstat (int fd, struct stat *pStat)    {        pStat->st_mode = S_IFCHR;        return 0;    }    int _close(int)    {        return -1;    }    int _write (int fd, char *pBuffer, int size)    {        for (int i = 0; i < size; i++)        {            while (!(USART1->SR & USART_SR_TXE))            {            }            USART_SendData(USART1, pBuffer);        }        return size;    }    int _isatty (int fd)    {        return 1;    }    int _lseek(int, int, int)    {        return -1;    }    int _read (int fd, char *pBuffer, int size)    {        for (int i = 0; i < size; i++)        {            while ((USART1->SR & USART_SR_RXNE) == 0)            {            }            pBuffer = USART_ReceiveData(USART1);        }        return size;    }    caddr_t _sbrk(int increment)    {        extern char end asm("end");        register char *pStack asm("sp");        static char *s_pHeapEnd;        if (!s_pHeapEnd)            s_pHeapEnd = &end;        if (s_pHeapEnd + increment > pStack)            return (caddr_t)-1;        char *pOldHeapEnd = s_pHeapEnd;        s_pHeapEnd += increment;        return (caddr_t)pOldHeapEnd;    }}

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

63

主题

106

帖子

3

粉丝