undefined reference to “only some math.h” functions

前端 未结 4 643
说谎
说谎 2020-12-06 06:06

I am having a strange problem.

The math libraries has been added to my makefile.

# include standard C library
LDFLAGS += -lc
# include standard math          


        
4条回答
  •  臣服心动
    2020-12-06 06:32

    The linker isn't complaining about pow((double) 2, (double) 3) because the compiler is replacing it with a constant 8.0. You shouldn't depend on this behavior; instead, you should always use the -lm option properly. (BTW, that's more clearly written as pow(2.0, 3.0).

    Consider the following program:

    #include 
    #include 
    int main(void) {
        double x = 0.1;
        printf("%g\n", pow(2.0, 3.0));
        printf("%g\n", asin(x));
        return 0;
    }
    

    When I compile and link it on my system using

    gcc c.c -o c
    

    I get:

    /tmp/ccXx8ZRL.o: In function `main':
    c.c:(.text+0x36): undefined reference to `asin'
    collect2: ld returned 1 exit status
    

    Note that it complains about asin but not about pow.

    If I change the pow call to pow(x, 3.0), I get:

    /tmp/ccOeSaBK.o: In function `main':
    c.c:(.text+0x24): undefined reference to `pow'
    c.c:(.text+0x52): undefined reference to `asin'
    collect2: ld returned 1 exit status
    

    Normally if you want to call a standard math library function, you need to have #include at the top of the source file (I presume you already have that) and you need to pass the -lm option to the compiler after the file that needs it. (The linker keeps track of references that haven't been resolved yet, so it needs to see the object file that refers to asin first, so it can resolve it when it sees the math library.)

    The linker isn't complaining about the call to pow(2.0, 3.0) because gcc is clever enough to resolve it to a constant 8.0. There's no call to the pow function in the compiled object file, so the linker doesn't need to resolve it. If I change pow(2.0, 3.0) to pow(x, 3.0), the compiler doesn't know what the result is going to be, so it generates the call.

提交回复
热议问题