重新定义gcc-arm-none-eabi的stdlibc的某些功能

kyb*_*kyb 1 embedded gcc arm libc stm32

STM32芯片(以及许多其他芯片)具有硬件随机数发生器(RNG),它比libc提供的软件RNG更快,更可靠。编译器对硬件一无所知。

有没有办法重新定义的实现rand()

还有其他硬件模块,即实时时钟(RTC),可以为提供数据time()

Cli*_*ord 5

You simply override them by defining functions with identical signature. If they are defined WEAK in the standard library they will be overridden, otherwise they are overridden on a first resolution basis so so long as your implementation is passed to the linker before libc is searched, it will override. Moreover .o / .obj files specifically are used in symbol resolution before .a / .lib files, so if your implementation is included in your project source, it will always override.

您应该小心以使实现的语义正确。例如,rand()将有符号整数0返回RAND_MAX,这与RNG硬件完全不同。由于RAND_MAX是宏,因此对其进行更改将需要更改标准标头,因此您的实现需要实施现有的RAND_MAX。

使用STM32标准外设库的示例:

#include <stdlib.h>
#include <stm32xxx.h> // Your processor header here

#if defined __cplusplus
extern "C"
{
#endif

static int rng_running = 0 ;

int rand( void )
{
    if( rng_running == 0 )
    {
        RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE);
        RNG_Cmd(ENABLE);
        rng_running = 1 ;
    }
    while(RNG_GetFlagStatus(RNG_FLAG_DRDY)== RESET) { }

    // Assumes RAND_MAX is an "all ones" integer value (check)
    return (int)(RNG_GetRandomNumber() & (unsigned)RAND_MAX) ;
}

void srand( unsigned ) { }

#if defined __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

对于time()类似的应用,在带有C的嵌入式应用程序中的time()函数问题上有一个示例