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.
<rt id="pwjBlLZ"><small id="pwjBlLZ"></small></rt>
<acronym id="pwjBlLZ"></acronym><rt id="pwjBlLZ"></rt>
<tr id="pwjBlLZ"><optgroup id="pwjBlLZ"></optgroup></tr><tr id="pwjBlLZ"><optgroup id="pwjBlLZ"></optgroup></tr><acronym id="pwjBlLZ"><small id="pwjBlLZ"></small></acronym>
<acronym id="pwjBlLZ"><optgroup id="pwjBlLZ"></optgroup></acronym>
<option id="pwjBlLZ"></option>
<tr id="pwjBlLZ"><optgroup id="pwjBlLZ"></optgroup></tr>
<acronym id="pwjBlLZ"><small id="pwjBlLZ"></small></acronym><acronym id="pwjBlLZ"></acronym>
<acronym id="pwjBlLZ"><small id="pwjBlLZ"></small></acronym>
  • 6512882421 2018-04-19
  • 4659652420 2018-04-19
  • 2967832419 2018-04-19
  • 8339042418 2018-04-19
  • 8147112417 2018-04-19
  • 2774752416 2018-04-19
  • 4316132415 2018-04-19
  • 6265742414 2018-04-19
  • 1875142413 2018-04-19
  • 4146552412 2018-04-19
  • 8205662411 2018-04-19
  • 959982410 2018-04-19
  • 7153742409 2018-04-19
  • 9349932408 2018-04-18
  • 6024052407 2018-04-18
  • 2113432406 2018-04-18
  • 7629172405 2018-04-18
  • 163882404 2018-04-18
  • 3515922403 2018-04-18
  • 5047802402 2018-04-18