I have the following source code:
foo.hvoid foo();foo.cpp#include "foo.h" #include <iostream> void foo(){ std::cout << "This is foo" << std::endl; }main.cpp:#include "foo.h" int main(){ foo(); return 0; }
Then I run the following command to produce both static and shared versions of foo.cpp:
g++ -c -fPIC foo.cpp
ar rvs libfoo.a foo.o
g++ -shared -o libfoo.so foo.o
g++ -c main.cpp
If I try to generate an executable using the static libfoo.a and main.o, the order of the object files and library file matters:
g++ main.o libfoo.a -o main # works
g++ libfoo.a main.o -o main # fails with undefined references to `foo()`
As explained in this post, the order matters.
However, if I try to build an executable using the shared libfoo.so and main.o, the order of object file and library file doesn't matter any more:
g++ main.o libfoo.so -o main # works
g++ libfoo.so main.o -o main # also works without errors
Does this mean that the order is not important when we link object file and shared libraries? Or this is a just a special case or some coincidence I am not aware of?
The above code and command is tested on the following platform:
- Linux: CentOS 7.4
- gcc: 7.3.1 or 4.8.5 (both tested)