1

I am using Code::Blocks 20.03 on Linux. When I try to compile the following code using the Build (F9) function I get undefined reference to 'sqrt':

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

main() {
    int a = 5;
    float b = sqrt(a);
    printf("%f", b);
}

When I put 5 in place of the a in sqrt, the code compiles and runs. When I copy this code to an online compiler, it runs. When I manually gcc code.c -o code -lm, the code runs.

I'm tempted to believe that the problem is with CodeBlocks, however, I also realise that I'm a newbie to programming and might not have set everything up right. What else could I try to be able to make conclusions here and hopefully to find a solution?

O1G
  • 71
  • 1
  • 7
  • 3
    My guess is that CodeBlocks does not add `-O2` and that when `5` constant is used GCC calculates sqrt at compile time (https://en.wikipedia.org/wiki/Constant_folding) but when a variable is used it cannot optimize it and needs `-lm`. – Arkadiusz Drabczyk Apr 29 '20 at 22:23
  • 1
    Try going Project -> Build Options -> Linker Tab and add '-lm' (without the quotes) to Other Linker Options – Swordelf Apr 29 '20 at 22:31
  • @kaylum, those instructions did help, adding 'm' as the library name. I guess for my problem it is more suitable to change the Linker settings in Settings > Compiler rather than for each project as math.h is a quiet often used library so I don't have to do it every time. Thanks for the help! – O1G Apr 29 '20 at 22:35

0 Answers0