0

Possible Duplicate:
C programming sqrt function

i'm facing a weird problem in C. I've included the library in the header, and for example the pow(x,n) function works as well. On the other hand ,the next code does does not run at all:

float calcArea(double edgeA){
    double s=edgeA;
    float area = sqrt(s);
    return area;
}

But when I change sqrt(s) to sqrt(45) (or any other natural number) it doesn't make any problem. I've also checked the sqrt() function more few times, and it's still doesn't as long as the argument is a variable.

Any suggestion for solving this problem will be helpful, Thanks in advance

EDIT : I'm using Eclipse

Community
  • 1
  • 1
Itamar
  • 524
  • 1
  • 9
  • 21

2 Answers2

4

You should tell the compiler to link the math library. On Linux, you should compile with

   gcc -Wall -g yoursource.c -o yourprog -lm

The order of arguments to gcc is important: first the source files, then the object files, then the libraries from higher-level to lower-level.

As to why the error don't happen if using sqrt(42) it is because gcc might constant-fold and inline it.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I'm working on windows , how could I link the compiler with the math library ? Thanks ! – Itamar Nov 05 '12 at 08:05
  • 2
    It is compiler specific, and I can't give details. I never used Windows. BTW, you may find interesting to use GNU/Linux: all programs are free software, and you can study their source code and improve them. – Basile Starynkevitch Nov 05 '12 at 08:06
3

you should link the math library when compiling

-lm

You didn't say which compiler you were using, but for visual studio you can try the following:

http://www.steptools.com/support/stdev_docs/help/settings_vc10.html#link

Edit: For eclipse see the HELP

iabdalkader
  • 17,009
  • 4
  • 47
  • 74