GCC Shared Library Problems

2019-07-11 21:36发布

问题:

I'm trying to create a shared library on ubuntu using gcc
I just have one simple class(shared.h and shared.cpp) and one client to use it (main.cpp)
This is my makefile and I'm still not able to to get the program to compile.

all:
    #compile object(fPIC: creates position independent code)
    gcc -fPIC -Wall -g -c shared.cpp

    #compile shared library
    gcc -shared -Wl,-soname,libshared.so.1 -o libshared.so.1.0.1 shared.o -lc

    #link shared library
    gcc -g -o main main.cpp -L. -lshared
  • I'm confident the first line is correct
  • I am unsure what "-lc" does. I think it passes something to the linker?
  • I don't want to install the library, I just want to be able to link it from the current directory. I have tried: export LD_LIBRARY_PATH=.
    but it does not seem to make a difference. Everything is in the current directory.

    ERROR: /usr/bin/ld: cannot find -lshared

how do I get the compiler to check the current directory for my library?

回答1:

The problem is not that it's not looking in the directory, the problem is that you've named the library "libshared.so.1.0.1". When you use -lshared, it's looking for a file named 'libshared.so' or 'libshared.a' in the library search path.

Most of the time, when using versioned system libraries, you'll provide a link to the latest one as 'libshared.so', even if you have installed 'libshared.so.1' or 'libshared.so.1.0.1'.

In your case, if you continue to leave the file named 'libshared.so.1.0.1', you'll want to create 2 symbolic links:

  1. libshared.so - So that the library can be found using ld
  2. libshared.so.1 - Since you declared the SO name as libshared.so.1 when building it, you need to provide this link, otherwise, the executable will not be able to find the proper shared library at runtime.


回答2:

You don't write any dependencies, which is the purpose of Makefile-s. And you probably need to force the run path Perhaps something like

 .PHONY: all clean
 CXX=g++
 CXXFLAGS=-g -Wall
 all: main
 main: main.o libshared.so
        $(LINK.cpp) -o $@ $< -Wl,-rpath,. -L. -lshared
 libshared.so: shared.pic.o
        $(LINK.cpp) -shared -o $^ $< 
 main.o: main.cc shared.hh 
 %.pic.o: %.cc
        $(CXX) $(CXXFLAGS) -fPIC -c -o $@ $<
 #
 clean:
        rm -f *.o *.so main *~