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?

3
  • You're doing it right and the order matters due to "historical reasons". I think they just avoid fixing it out of nostalgia now Commented Mar 22, 2021 at 9: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... Commented Mar 22, 2021 at 9:39
  • This has taken a lot of hours of my life too :) But yeah the order does matter unfortunately Commented Mar 22, 2021 at 9:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So thats the reason, but it's still a matter of implementation right?
Does gcc make any guarantee that it processes the commands left to right though?
@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."
Aha, nice. I thought this was just one of those many undocumented things in gcc.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.