sqrt() function not working with variable argument

2019-01-09 13:14发布

I don't know if I'm missing something obvious, but it appears that I'm unable to compute square roots of a variable in C; the sqrt() function only seems to work on constants. This is my code:

#include <math.h>
#include <stdio.h>

int main()
{
    double a = 2.0;
    double b = sqrt(a);
    printf("%f", b);
    return 0;
}

When I run this program, I get the following error:

gcc -Wall -o "test2" "test2.c" (in directory: /home/eddy/Code/euler)
/tmp/ccVfxkNh.o: In function `main':
test2.c:(.text+0x30): undefined reference to `sqrt'
collect2: ld returned 1 exit status
Compilation failed.

However, if I replace the argument in sqrt() with a constant such as 2.0 for example, (b = sqrt(2.0)), then it works fine. Is sqrt() not supposed to work with variables or something?

Thanks for the help

8条回答
老娘就宠你
2楼-- · 2019-01-09 13:51

You probably need to add -lm when you compile. When you take the square root of a constant, the compiler is optimizing the code by taking the square root while it compiles, so it doesn't use sqrt at all.

查看更多
在下西门庆
3楼-- · 2019-01-09 13:59

In case of gcc you need to link the library.

gcc filename.c -lm .

However in case of g++ no need to link the library so this will work fine :

g++ filename.c -o filename Once compilation is successful.

To run simply enter ./filename in G++. and enter ./a.out in Gcc.

查看更多
登录 后发表回答