3

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?

Aayush Jain
  • 143
  • 7
  • You're doing it right and the order matters due to "historical reasons". I think they just avoid fixing it out of nostalgia now – M.M Mar 22 '21 at 09:38
  • the `-lm` makes gcc look in that library for things it needs up to that point in the command line... so `gcc -o a.out -lm` needs nothing from the math library... and `gcc -o a.out -lm MyCode.c` doesn't use the library when compiling MyCode.c. **TLDR** Always apecify the libraries at the end of the command line: `gcc -std=c11 -pedantic -Wall -Wextra -O... -f... -o executable *.c -l...` – pmg Mar 22 '21 at 09:39
  • This has taken a lot of hours of my life too :) But yeah the order does matter unfortunately – Serve Laurijssen Mar 22 '21 at 09:45

1 Answers1

2

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.

0___________
  • 34,740
  • 4
  • 19
  • 48
  • So thats the reason, but it's still a matter of implementation right? – Serve Laurijssen Mar 22 '21 at 09:47
  • Does gcc make any guarantee that it processes the commands left to right though? – Lundin Mar 22 '21 at 09:49
  • 1
    @Lundin I think yes: (from the gcc documentation) `"It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, ‘foo.o -lz bar.o’ searches library ‘z’ after file foo.o but before bar.o. If bar.o refers to functions in ‘z’, those functions may not be loaded."` – 0___________ Mar 22 '21 at 09:54
  • Aha, nice. I thought this was just one of those many undocumented things in gcc. – Lundin Mar 22 '21 at 10:01