0

This has been solved

I am trying to use exp() from math.h in C, but it is failing to compile whenever I pass a variable as the argument. The following code works just fine

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

int main() {
    printf("exp(x) = %f\n", exp(12));

    return 0;
}

While this code fails to compile

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

int main() {
    double x = 12.0;
    double result;
    result = exp(x);

    printf("exp(x) = %f\n", result);

    return 0;
}

I am compiling with this

gcc -g -std=c99 -fsanitize=address -Wall -Wextra -o main dummy.c

and am getting the following compilation error (the warning is kept for completeness)

dummy.c: In function ‘main’:
dummy.c:6:9: warning: variable ‘result’ set but not used [-Wunused-but-set-variable]
  double result;
         ^~~~~~
/usr/bin/ld: /tmp/ccyFoBpl.o: undefined reference to symbol 'exp@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

Edit:

I've tried adding the -lm flag as suggested in the comments, and I get a different error now.

/tmp/ccpBvvBq.o: In function `main':
/home/velcro/Documents/Undergrad/Math/DiffEq_292/lab2/dummy.c:8: undefined reference to `exp'
collect2: error: ld returned 1 exit status

Edit 2: I needed to add the -lm to the end of compilation command. Now everything works. For anyone else interested see the linked question in the comments. My final compilation command is

gcc -g -std=c99 -fsanitize=address -Wall -Wextra -o main dummy.c -lm
  • Add `-lm` to your `gcc` arguments. That solves the error and the warning. – user51187286016 Mar 31 '22 at 02:20
  • The dup is for a different function in the maths lib but the issue and fix is the same. Also, the reason why the first example doesn't have an error is because the compiler has almost certainly optimised out that call and replaced it with some inline code. – kaylum Mar 31 '22 at 02:21
  • Hmm I got the same error message. I also tried adding ```-ldl``` (seperately and together) and it persists – MrGorbunov Mar 31 '22 at 02:22
  • Please show your exact build command. `-lm` needs to be after `dummy.c` so please check that. – kaylum Mar 31 '22 at 02:23
  • Sorry I do get a different error message. I've just edited the post with it and am also looking further. – MrGorbunov Mar 31 '22 at 02:24
  • Yea I see now. I added -lm to the end of the command instead and it all worked, thanks! – MrGorbunov Mar 31 '22 at 02:27
  • Just to explain the "magic": `-l` in gcc links the `lib` object file against the object file that contains the `main()` function (to produce an executable). `libm` has the implementations of the `math.h` functions. But the object file containing `main` exists only **after** the compilation of the source file (here being `dummy.c`) so if you place `-lm` before, is ignored. I know, seems silly, right? – user51187286016 Mar 31 '22 at 02:35

0 Answers0