2 Replies - 1684 Views - Last Post: 01 October 2012 - 02:02 PM

#1 bjm62692  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 25
  • Joined: 23-September 12

undefined reference to 'sqrt' after #include <math.h>

Posted 01 October 2012 - 01:19 PM

This is the Include Section above the Main Function.
/*---------------
Include Section
----------------*/
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>




This is the Function with sqrt that is not working.
/*--------------------------- approx2 funtion --------------------------------
Purpose: Approximates value of pi using the square root equation
Returns: Approximate value of pi
----------------------------------------------------------------------------*/
long double approx2 (int terms) {
    long double pi2;
    long double num;
    long double denom;
    int i;
    num = 12;
    denom = 1;
    for (i = 1; i <= terms; i++) {
        if (i % 2 != 0 ) {
            pi2 += num / (denom * denom);
            }
        else {
            pi2 -= num / (denom * denom);
            }
        denom += 1.0;
        }
    pi2 = sqrt (pi2);
    return pi2;
}




This is the error code.
/tmp/ccSYh7w6.o: In function `approx2':
pi.c:(.text+0x2ac): undefined reference to `sqrt'
collect2: ld returned 1 exit status



I cannot seem to figure out why it does not like sqrt. I have tried looking it up, but I cannot find an explanation that apperently applies.

Is This A Good Question/Topic? 0
  • +

Replies To: undefined reference to 'sqrt' after #include <math.h>

#2 jimblumberg  Icon User is offline

  • member icon


Reputation: 3845
  • View blog
  • Posts: 11,753
  • Joined: 25-December 09

Re: undefined reference to 'sqrt' after #include <math.h>

Posted 01 October 2012 - 02:00 PM

The sqrt() function is not defined for use with the long double in C. You need to use long double sqrtl(long double x) for a long double.

Please note, unless your question is only related to Objective-C you should post in the C/C++ forum. You will have more views in the main C/C++ forum.

Jim
Was This Post Helpful? 0
  • +
  • -

#3 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2015
  • View blog
  • Posts: 3,041
  • Joined: 21-June 11

Re: undefined reference to 'sqrt' after #include <math.h>

Posted 01 October 2012 - 02:02 PM

When using gcc/glibc, you'll need to link against the m library (using the -lm compiler switch) when compiling code that uses math functions.

View Postjimblumberg, on 01 October 2012 - 11:00 PM, said:

The sqrt() function is not defined for use with the long double in C. You need to use long double sqrtl(long double x) for a long double.


That's not what's causing the linker error though.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1