MDK 中 [WEAK] 的作用

简介

__weak 或 [weak] 具有相同的功能,用于定义变量或者函数,常见于定义函数,在 MDK 链接时优先链接定义为非 weak 的函数或变量,如果找不到则再链接 weak 函数。

在STM32 的启动文件中有以下定义:

; Reset handler
Reset_Handler   PROC
                EXPORT  Reset_Handler             [WEAK]
                IMPORT  __main
                IMPORT  SystemInit
                LDR     R0, =SystemInit
                BLX     R0               
                LDR     R0, =__main
                BX      R0
                ENDP
                
; Dummy Exception Handlers (infinite loops which can be modified)

NMI_Handler     PROC
                EXPORT  NMI_Handler                [WEAK]
                B       .
                ENDP
HardFault_Handler
                PROC
                EXPORT  HardFault_Handler          [WEAK]
                B       .
                ENDP
MemManage_Handler
                PROC
                EXPORT  MemManage_Handler          [WEAK]
                B       .
                ENDP

如上所述,如果链接时没有找到与 [weak] 定义相同的函数名,那么此函数的功能即为“ B . ”循环。

再举一个关于 __weak 的例子(来自百度):

weakTest.c 文件:

__weak void weakFunctioin(void){            //定义为__weak类型的函数
    logInfo("print weakFunction
");
}

int weakFunctionTest(unsigned int tst){


    logInfo("print A
");
    if (tst) {
        logInfo("print B
");
        weakFunctioin();                   //调用函数
        logInfo("print C
");
    }else{
        logInfo("print D
");
    }
    logInfo("print E
");
    return 0;
}

main.c 文件:

void weakFunctioin(void){                 //定义为正常的函数

    logInfo("print nonWeakFunction
");
    return;
}

int main(void){


    logInit(logLevelDebug);
    logInfo("Build @ %s %s,system start
", __DATE__, __TIME__);

    weakFunctionTest(1);
    logInfo("Build @ %s %s,system stop
", __DATE__, __TIME__);
    while(1);
    return 0;
}

编译链接运行后,结果如下:

-I: Build @ Jun 12 2017 15:14:18,system start 
-I: print A 
-I: print B 
-I: print nonWeakFunction 
-I: print C 
-I: print E 
-I: Build @ Jun 12 2017 15:14:18,system stop
原文地址:https://www.cnblogs.com/GyForever1004/p/8893866.html