Search code examples
cmicrocontrollerstm32f4discovery

giving parameters into math function


If I call in C, math function `"trunc" in math library is define as:

extern double trunc _PARAMS((double));

and in my main file call it:

int i = (int)trunc(2.5);

It works fine, no problems. But if I try to pass double passively, like:

double d = 2.5;
int i = (int)trunc(d);

It won't work?!? In my microprocessor STM32F4 IDE it goes in debugger mode into:

 Infinite_Loop:
 b  Infinite_Loop

and it stuck there. I also change double and try float, int, unit8_t,... no one isn't working. Also other math functions will work fine as I call them like this:

i =  sin(1);
i =  cos(1);

But, it will crashed the same, if called like this:

int a = 1;
i = sin(a);
i = cos(a);

I am running this code on microprocessor STM32F4 Discovery,IDE is Eclipse Ac6.


Solution

  • If you refer the man page for trunc() you should note that, it says

    Link with -lm

    So, make sure that you are linking with -lm.

    Secondly, when synopsis say double trunc(double x);, there is no point in trying it out with other data types.

    If you want to try with other data types then you should look for these variants:

    float truncf(float x);
    long double truncl(long double x);
    

    Test code:

    #include<stdio.h>
    #include<math.h>     
    
    int main(void)
    {
        // using trunc function which return
        // Truncated value of the input 
        double d = 2.7;
        printf(" Truncated value is %d \n", (int)trunc(d)); 
    
        return 0;
    }
    

    This generated an output:

     Truncated value is 2
    

    And it was compiled with gcc version 5.3.0

    When I compile the same code gcc version 7.2.0 without -lm option, I get following warning:

    undefined reference to `trunc'
    error: ld returned 1 exit status