问题
I'm using g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609.
I have a shared library lib2
:
lib2.h:
#pragma once
class Lib2
{
public:
Lib2();
};
lib2.cpp:
#include "lib2.h"
Lib2::Lib2()
{
}
I have a shared library lib1
that uses and so needs lib2
:
lib1.h:
#pragma once
class Lib1
{
public:
Lib1();
};
lib1.cpp:
#include "lib1.h"
#include "lib2.h"
Lib1::Lib1()
{
Lib2 lib2;
}
Now I have a program that uses lib1
, and so does not "directly" use lib2
but would need it at runtime.
main.cpp:
#include "lib1.h"
int main(int argc, char *argv[])
{
Lib1 lib;
return 0;
}
Let's compile this:
I compile lib2
:
g++ -fPIC -O -g lib2.cpp -c -o lib2.o
g++ -shared lib2.o -L. -o liblib2.so
I compile lib1
, linking with lib2
:
g++ -fPIC -O -g lib1.cpp -c -o lib1.o
g++ -shared lib1.o -L. -llib2 -o liblib1.so
Now I compile main
:
g++ -fPIC -O -g main.cpp -c -o main.o
And when I try to create the executable:
g++ main.o -L. -llib1 -o main
I get the error:
./liblib1.so : référence indéfinie vers « Lib2::Lib2() »
collect2: error: ld returned 1 exit status
If I run:
g++ main.o -L. -llib1 -llib2 -o main
it works. But why should my program explcitely link to lib2
while it does not directly use it? Am I doing something wrong? Under Windows, main only links with lib1.lib
, lib2.lib
is not needed when creating the executable.
Please do not mark as duplicate of Linking a shared library with another shared lib in linux. I checked this post, it mentions that -fPIC
has to be used, and I'm using it.
来源:https://stackoverflow.com/questions/65603457/c-linux-lib1-shared-library-uses-shared-library-lib2-main-program-uses-lib1