C++ 在linux上编译和使用共享库

C++ 在linux上编译和使用共享库,c++,linux,shared-libraries,dynamic-library,C++,Linux,Shared Libraries,Dynamic Library,我正在尝试在linux上编译和使用共享库。根据linux文档项目,我创建了以下文件: //--main.cpp--// #include "header.h" int main(){ char * str= "This is a string\n"; printStr(str); } //--header.h--// void printStr(char *); //--foo.cpp--// #include<stdio.h> extern int var;

我正在尝试在linux上编译和使用共享库。根据linux文档项目,我创建了以下文件:

//--main.cpp--//
#include "header.h"
int main(){
    char * str= "This is a string\n";
    printStr(str);
}

//--header.h--//
void printStr(char *);

//--foo.cpp--//
#include<stdio.h>

extern int var;

void printStr(char * str){
    printf("%s", str);
}

//--Makefile--//
bin: main.o foo.so
    g++ -o bin main.o -L. -lfoo.so.1
main.o:main.cpp
    g++ -c main.cpp
foo.so: foo.o
    g++ -shared -Wl,-soname,libfoo.so.1 -o libfoo.so.1.0.1 foo.o
foo.o:foo.cpp
    g++ -fPIC -c foo.cpp
clean:
    rm -f *.o *.so* bin

如果我试图将libfoo.so.1.0移动到/usr/loca/lib中,我会遇到同样的错误。请帮帮我。

第三个文件是否应该注释为main.cpp作为header.cpp?@BlAcKBirD我已经更新了它。-lxxx链接到libxxx.so,而不是xxx.so。@Massa我知道。我正在我的Makefile中创建libfoo.so.1.0,作为g++-shared-Wl,-soname,libfoo.so.1-o libfoo.so.1.0.1 foo.oRepeating@Massa,-lfoo.so.1将链接到libfoo.so.1.so
g++ -shared -Wl,-soname,libfoo.so.1 -o libfoo.so.1.0.1 foo.o
g++ -o bin main.o -L. -lfoo.so.1
/usr/bin/ld: cannot find -lfoo.so.1
collect2: error: ld returned 1 exit status
make: *** [bin] Error 1