1

I have the following two files:

// t.c
#include<stdio.h>

extern int x;

int main(void)
{
    printf("%d\n", x);
}
// tt.c
int x=4;

And then I compile it into two object files with:

$ gcc -c tt.c t.c

So now I have two object files, tt.o and t.o. When I do the following to build an executable:

$ gcc tt.o t.o -o out

How does the linker resolve the definition of x? Does it basically do a "two-pass" where it saves all global variables with external linkage first, and then does a lookup in each file that needs an external definition, or what's the process that happens to resolve those lookups?

M.M
  • 138,810
  • 21
  • 208
  • 365
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • 1
    For speed, it's usually one-pass. Special handling for `.a` files than have had `ranlib` applied to them. Or, there are some options for multi-pass scan. For a more detailed explanation of what happens, see my answer: https://stackoverflow.com/questions/34164594/gcc-ld-method-to-determine-link-order-of-static-libraries/34168951#34168951 – Craig Estey Feb 12 '21 at 21:20
  • @CraigEstey if it's one-pass though, how would it know which order to process the files in? For example, if it does `t.c` first and looks up the symbol `x` it won't find it...until it hits file `tt.c`...and maybe that file has dependencies in other files that it hasn't encountered yet...Or maybe it reads all the symbol tables first and builds that and after that does a one-pass? – samuelbrody1249 Feb 12 '21 at 21:29
  • 1
    It processes them in `argv` order. That's why `cc -o xfile -lm math.o math2.o` doesn't work if the `.o` files need functions from `libm.a` – Craig Estey Feb 12 '21 at 21:36
  • 2
    Order of lib*.a libraries matters because the linker is making decisions about whether or not to include each *.o object packed within the library. Plain object *.o files directly on the command line will definitely be included. Fix up of undefined symbols from all these objects is a different thing, but I wouldn't say there's as much of an "order" to that. – aschepler Feb 12 '21 at 21:37

0 Answers0