Home > c programming language > Using sqrt in C lang.

Using sqrt in C lang.

Problem
The following code compiles with “gcc in.c“:

#include 
#include 

int main()
{
    double result = sqrt(9.0);
    printf("%lf\n", result);

    return 0;
}

The following code drops an error if you try to compile with “gcc in2.c“:

#include 
#include 

int main()
{
    double value = 9.0;
    double result = sqrt(value);
    printf("%lf\n", result);

    return 0;
}

The error message says: “undefined reference to `sqrt'”.

Solution and Explanation
In the second case, compile it with “gcc -lm in2.c“, which links the math library. But why does the first example work? In that case the compiler figures out (knows) the value of the square root operation and replaces the function call with a constant 3.0 value. The optimizer is that clever :) In the second case however it tries to call the sqrt() function but it’s not found. If you link the math library, it’ll find it.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: