1 year ago

#357016

test-img

MrGorbunov

Unable to use exp() with a variable

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

c

function

compiler-errors

arguments

math.h

0 Answers

Your Answer

Accepted video resources