如何使用gcc创建和使用自定义共享库?

时间:2016-03-30 09:21:24

标签: c++ c linux gcc makefile

我试图编写一个简单的示例共享库makefile,但我遇到了一些错误而无法处理它,请帮助我,谢谢。

这是我的makefile:

<http://someurl|like this>

这个makefile支持4个操作:

  • (1)make basic:basic.exe
  • (2)make static:static.exe
  • (3)make shared:shared.exe
  • (4)make clean:rm objects

(3)可以make,但是当我尝试&#34; ./ shared.exe&#34;时,它说:./ shared.exe:加载共享库时出错:libshared.so:无法打开共享对象file:没有这样的文件或目录

这是我的示例代码和makefile链接:https://github.com/zhaochenyou/Tips/tree/master/tool_chain/make/basic

2 个答案:

答案 0 :(得分:3)

Make已针对您需要的大部分内置规则,以下内容应与您在共享和非共享之间切换时需要重新制作.o文件的警告一起使用

CXXFLAGS := -std=c++11 -Wall -g -pthread
LDFLAGS  := -g -pthread

basic.exe static.exe shared.exe: exampleMain.o
basic.exe:  example.o
static.exe: libstatic.a
shared.exe: libshared.so

libstatic.a: libstatic.a(example.o)

libshared.so: CXXFLAGS += -fPIC
libshared.so: LDFLAGS += -shared -Wl,-soname,libshared.so
libshared.so: example.o

basic.exe static.exe shared.exe libshared.so:
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

clean: ; $(RM) exmapleMain.o example.o libshared.so libstatic.a basic.exe static.exe shared.exe

重要提示:从不在删除时使用通配符,您可能会删除不负责的内容。

至于错误读取this,特别是“安装和使用共享库”部分。

答案 1 :(得分:0)

在@ user657267的帮助下,我编写了一个示例makefile,它支持以下内容:

  • make basic.exe
  • make libstatic.a
  • make static.exe
  • make libshared.so
  • make shared.exe

源cpp文件是example.hpp,example.cpp,exampleMain.cpp。这里有一个简单的示例函数和一个main函数。 这是主文件:

# additional compile flags
# CFLAGS for c
# CXXFLAGS for c++
CXXFLAGS := -std=c++11 -Wall -g -pthread -I./

# additional link flags
LDFLAGS  := -pthread

# dependent object
basic.exe static.exe shared.exe: exampleMain.o
basic.exe:  example.o
static.exe: libstatic.a
shared.exe: libshared.so

# additional link flags for shared.exe
# NOTICE: -Wl,-rpath=./ is for libshared.so runtime path
shared.exe: LDFLAGS += -L./ -Wl,-rpath=./

# NOTICE: this command also works:
# libstatic.a: libstatic.a(example.o)
libstatic.a: example.o
    ar rcs libstatic.a example.o

# additional compile and link flags for libshared.so
libshared.so: CXXFLAGS += -fPIC
libshared.so: LDFLAGS += -shared -Wl,-soname,libshared.so
# dependent object
libshared.so: example.o

# $^: all dependent objects
# $@: all target objects
# $(CXX): default c++ compiler
# $(LDLIBS): default c++ libraries
basic.exe static.exe shared.exe libshared.so:
    $(CXX) $(CXXFLAGS) $(LDFLAGS) $^ $(LDLIBS) -o $@

# $(RM): default rm command
clean:
    $(RM) exmapleMain.o example.o libshared.so libstatic.a basic.exe static.exe shared.exe
相关问题