Compile c code with a float instead of double

I have a long digital integration circuit written in C. I would like to test my algorithm with floating point precision. Is there a way to tell gcc to omit every double event on a float in the whole program?

+4
gcc floating-point
Jul 11 '14 at 1:37
source share
2 answers

You cannot safely do this without changing the source code, but it should not be terribly difficult to do.

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

As a stix answer , you can add a typedef either at the top of your program (if it is one source file) or in some header that #include ed with all the corresponding source files:

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

Then go to the source code and change each occurrence of double to real . (Be careful when doing blind global search and replace.)

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

  typedef float real; 

and recompile to use float , not double .

It is not quite that simple. If you use functions declared in <math.h> , you need to use the correct function for any type of floating point that you use; e.g. sqrt() for double , sqrtf() for float , and sqrtl() for long double .

If your compiler supports it, you can use the <tgmath.h> header, which defines sample macros that correspond to the math functions from <math.h> . If you use <tgmath.h> , then sqrt(x) allow you to call the correct square root function depending on the type of argument.

+4
Jul 11 '14 at 2:00
source share
 typedef double float; 

Before any duplicates that you want to replace should work, however, they should be warned that this may confuse some external libraries.

In the future, the best approach is to define your own float type:

 #ifdef USE_FLOATS typedef float MyFloatType; #else typedef double MyFloatType; #endif 

Or use templates that have the added benefit of allowing you to change the code at runtime to use one or the other.

0
Jul 11 '14 at 1:42 on
source share



All Articles