naked 函数

本文详细介绍了裸函数的概念及其在C/C++中的应用,包括如何通过裸函数免去编译器默认的工作,以及如何在函数调用中正确地平衡堆栈。通过一个简单的例子,展示了裸函数如何在函数内直接进行堆栈操作,从而实现更高效且灵活的代码编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vc 提供了一种叫做naked函数的声明。naked意思为赤裸的意思,需要程序员管理堆栈,退出时需要显示调用ret,以及平衡堆栈。

当然带来的好处是免去了编译器默认为我们做的那些不必要的工作(很多费代码)。

 

以下是一个简单的naked函数的例子

 

 

 

 naked 函数默认为__cdecl调用,需要调用者平衡堆栈(如果使用call调用时)。

 

 

 

在调用sum函数后,需要将esp加上8(两个dword的长度)。

 

另外注意的是,调用C函数是,不能直接使用call printf,而需要使用 call dword ptr[printf]

 

Build started: Project: project *** Using Compiler 'V6.16', folder: 'D:\kile-v5\ARM\ARMCLANG\Bin' Build target 'Target 1' Start/core_cm3.c(445): error: non-ASM statement in naked function is not supported uint32_t result=0; ^ Start/core_cm3.c(442): note: attribute is here uint32_t __get_PSP(void) __attribute__( ( naked ) ); ^ Start/core_cm3.c(465): error: parameter references not allowed in naked functions "BX lr \n\t" : : "r" (topOfProcStack) ); ^ Start/core_cm3.c(461): note: attribute is here void __set_PSP(uint32_t topOfProcStack) __attribute__( ( naked ) ); ^ Start/core_cm3.c(479): error: non-ASM statement in naked function is not supported uint32_t result=0; ^ Start/core_cm3.c(476): note: attribute is here uint32_t __get_MSP(void) __attribute__( ( naked ) ); ^ Start/core_cm3.c(499): error: parameter references not allowed in naked functions "BX lr \n\t" : : "r" (topOfMainStack) ); ^ Start/core_cm3.c(495): note: attribute is here void __set_MSP(uint32_t topOfMainStack) __attribute__( ( naked ) ); ^ Start/core_cm3.c(509): warning: no previous prototype for function '__get_BASEPRI' [-Wmissing-prototypes] uint32_t __get_BASEPRI(void) ^ Start/core_cm3.c(509): note: declare 'static' if the function is not intended to be used outside of this translation unit uint32_t __get_BASEPRI(void) ^ static Start/core_cm3.c(524): warning: no previous prototype for function '__set_BASEPRI' [-Wmissing-prototypes] void __set_BASEPRI(uint32_t value) ^ Start/core_cm3.c(524): note: declare 'static' if the function is not intended to be used outside of this translation unit void __set_BASEPRI(uint32_t value) ^ static Start/core_cm3.c(5
06-28
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值