Quick question about linking in C program

I have a shared library that I built successfully called libcopy.so

When I link I used the following command:

gcc -L/home/host/OS/prog3/ -pthread -lcopy main.c

which fails saying that the function defined in my shared library cannot be found. However if I change up the ordering to:

gcc -L/home/host/OS/prog3/ -pthread main.c -lcopy

it compiles and works.

My question is why does -lcopy be AFTER the source file and why does it matter? All the tutorials I find do it this way(-l at end) but no explanation as to why it must be at the end. In my mind, it should'nt matter where it is.
Last edited on
I have found that the order of library args are important with gcc. The linker appears to make a single pass thru the args.
I eventually found an answer that makes sense to me. I'll explain here for anyone else who stumbles upon this.

My main.c function was calling a function in libcopy.so. That's what I said above. The gcc linker uses an optimized algorithm to link things in libraries and source code.

Here's a summery:
1. The linker will look at the first source file/library and make note of any dependencies that need to be resolved
2. the linker will then move to the next source file/library and resolve these dependencies if they can be.
3. go back to 1 until no more files to look at.

My problem was the dependency was in main.c but it could'nt be resolved because gcc didn't keep up with functions unless they were dependent.

To summerize, gcc's linker doesn't keep up with all functions to fix dependencies, but rather keeps a list of functions that need to be defined. Thus, in order to successfully compile and link code you must provide gcc your files like so: gcc (dependent code) (code that defines dependent code).
Registered users can post here. Sign in or register to post.
  • 1007451581 2018-02-22
  • 8908121580 2018-02-22
  • 141161579 2018-02-22
  • 9421578 2018-02-22
  • 2826901577 2018-02-22
  • 3647361576 2018-02-22
  • 5717551575 2018-02-22
  • 523811574 2018-02-22
  • 6439871573 2018-02-22
  • 8109431572 2018-02-22
  • 8757321571 2018-02-22
  • 5265111570 2018-02-22
  • 3351351569 2018-02-22
  • 5109361568 2018-02-22
  • 4455391567 2018-02-22
  • 9091121566 2018-02-22
  • 24791565 2018-02-22
  • 2486841564 2018-02-21
  • 9847231563 2018-02-21
  • 9264681562 2018-02-21