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.
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).