GCC error undefined reference to `sqrt' on changing command option order

Viewed 86

Why I am getting the following error

/tmp/ccuWdVB3.o: In function `test':
MyCode.c:(.text+0x1c): undefined reference to `sqrt'
collect2: error: ld returned 1 exit status

MyCode.c

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

int test(int input1)
{

  int x = 8;
  int z = sqrt(x);
    
}

int main(int argc, char * a[]) {

}

when running with command:

gcc -o a.out -lm MyCode.c

But when I am running the command

gcc MyCode.c -o a.out -lm

everything works fine. Why the order of "MyCode.c" cli option is important here ? Or Am i doing something wrong?

1 Answers

Libraries are searched only once during the linking (they may contain millions of symbols and objects) and that is the reason why they should be specified as the last ones when all objects linker has to search for are already known. Searching the giant library for the symbols after every object file in the project would be extremely inefficient.

Related