在不修改源代码的情况下,不能安全地做到这一点,但这不应该是非常困难的。 / 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 $ c如果你的编译器支持它,你可以使用< 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代码
发布评论