内核中如何进行浮点数运算

本文介绍了在STM32(以mt6739为例)上进行浮点运算的条件,包括硬件浮点运算单元的支持、内核配置以及编译器设置。通过示例代码展示了浮点运算的过程,并强调了printk不支持直接打印浮点数,以及Makefile中启用浮点指令编译的必要性。

第一章 内核进行浮点运算的条件

现代处理器硬件已经支持浮点运算, 而且作为一个组件对待, 可选配, 根据需求和方案选型处理器时评估是否需要硬件支持。在STM系列浮点硬件单元叫做FPU(float process unit),ARM中归属协处理器。
如果要使用硬件浮点的话, 需要满足三个条件:

  1. 硬件要有浮点运算单元-------------通过测试代码运行计算结果正常,推测mt6739是支持的
  2. 内核要配置使能硬件浮点(主要设置协处理器)-------------看看对应的宏有没有float相关的,本文没有配置
  3. 编译器指定-mfloat-abi=softfp 或-mfloat-abi=hard 编译浮点指令而不是用函数替换!----------这是关键

第二章 浮点运算的示例-验证代码

注意1:printk不支持打印浮点数格式,只能转成int输出

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
static ssize_t float_math_read(struct class *cls,struct class_attribute *attr, char *buf)
{
	double a=3.3;
	float b=0.8;
	b=b*5-1.5;
	a=a*100/6;
	return scnprintf(buf, PAGE_SIZE, "b=%d a=%d\n",(int)b,(int)a);
}
static struct class_attribute device_attrs[] = {
	__ATTR(float_math, 0664, float_math_read, NULL),
	__ATTR_NULL,
};
static int __init hello_init(void)
{
	int ret = 0;
	struct class *hello_class;
	hello_class = class_create(THIS_MODULE, "hello");
	if (class_create_file(hello_class, &device_attrs[0]) != 0) {
		printk(KERN_ERR "sys creat file failed\n");
		ret = -1;
	}
	return ret;
}
static void __exit hello_exit(void)
{
	
}
module_init(hello_init);
module_exit(hello_exit);

Makefile文件增加编译浮点指令:

subdir-ccflags-y += -Werror
#这是关键
ccflags-y += -mfloat-abi=softfp
obj-y   +=  hello.o

使用adb计算浮点预算并输出结果:
1、adb root
2、adb shell
3、cat /sys/class/hello/float_math
输出结果:
b=2 a=55

第三章 总结

1、printk函数不支持打印浮点数
2、Makefile需要增加编译浮点指令

说明:本文基于mt6739进行测试

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值