用float而不是double来编译c代码 [英] Compile c code with float instead of double

查看:296
本文介绍了用float而不是double来编译c代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用C编写的冗长的数字集成方案。我想用浮点精度来测试我的算法。有没有办法告诉gcc在整个程序中降级每一个 double float 的事件?

解决方案

在不修改源代码的情况下,不能安全地做到这一点,但这不应该是非常困难的。 / p>

使用预处理器强制程序中的关键字 double 被视为 float 是一个坏主意;它会让你的程序难以阅读,如果你碰巧在任何地方使用 long double ,它将被视为 long float ,这是一个语法错误。



作为 stix的答案建议你可以在你的程序的顶部(如果它是一个单一的源文件),或者在的头文件中添加一个 typedef / code>由所有相关源文件编辑:

  typedef double real; / *或者选择一个不同的名称* / 

然后通过源代码并更改每个 double real 。 (注意做一个盲目的全局搜索和替换。)

确保程序仍然编译,运行并且在这个改变之后以相同的方式运行。然后你可以改变typedef为:

  typedef float real; 

并重新编译为使用 float 而不是 double



虽然这并不简单。如果你正在使用在< math.h> 中声明的函数,那么你需要使用正确的函数来处理你正在使用的任何浮点类型。例如, sqrt()用于 double sqrtf()用于 float sqrtl()用于 long double < tgmath.h> 标题,它定义了对应于< math.h> 的数学函数的 type-generic macros 。如果使用< tgmath.h> ,那么 sqrt(x)将解析为调用正确的平方根函数取决于参数的类型。


I have a lengthy numeric integration scheme written in C. I'd like to test my algorithm in floating point precision. Is there a way to tell gcc to demote every occurrence of double to float in the entire program?

解决方案

You can't safely do this without modifying your source code, but that shouldn't be terribly difficult to do.

Using the preprocessor to force the keyword double in your program to be treated as float is a bad idea; it will make your program difficult to read, and if you happen to use long double anywhere it would be treated as long float, which is a syntax error.

As stix's answer suggests, you can add a typedef, either at the top of your program (if it's a single source file) or in some header that's #includeed by all the relevant source files:

typedef double real; /* or pick a different name */

Then go through your source code and change each occurrence of double to real. (Be careful about doing a blind global search-and-replace.)

Make sure that the program still compiles, runs, and behaves the same way after this change. Then you can change the typedef to:

 typedef float real;

and recompile to use float rather than double.

It's not quite that simple, though. If you're using functions declared in <math.h>, you'll want to use the right function for whatever floating-point type you're using; for example, sqrt() is for double, sqrtf() is for float, and sqrtl() is for long double.

If your compiler supports it, you might use the <tgmath.h> header, which defines type-generic macros corresponding to the math functions from <math.h>. If you use <tgmath.h>, then sqrt(x) will resolve to call the correct square root function depending on the type of the argument.

这篇关于用float而不是double来编译c代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆