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

Page 1 of 1

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

### #1 bjm62692

Reputation: 0
• 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

Reputation: 4910
• Posts: 15,338
• 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

### #3 sepp2k

• D.I.C Lover

Reputation: 2307
• Posts: 3,568
• 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.

jimblumberg, 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.

Page 1 of 1

 .related ul{list-style-type:circle;font-size:12px;font-weight:bold;}.related li{margin-bottom:5px;background-position:left 7px!important;margin-left:-35px;}.related h2{font-size:18px;font-weight:bold;}.related a{color:blue;}