c - 将 .so 文件链接成可执行文件

标签 c makefile linker shared-libraries clang

我有在 clang 中使用 -fPIC 开关编译的目标代码,它也使用了 -shared 开关。然后我将所有这些链接到一个 .so 共享对象中。现在我想将其链接到一个可执行文件中,手册页告诉我我应该能够使用 ld 命令和 -l 开关。但是当我这样做时,出现以下错误:


ld -r -L./ -l:libmymath.so simpleone
ld: attempted static link of dynamic object `libmymath.so'
make: *** [simpleone] Error 1


我尝试用 -dy 开关做同样的事情,但它给了我同样的错误。 我真的不明白为什么这行不通。

这是我用来完成所有这些的 makefile。

CC= clang 
LD= ld -r
CFLAGS= -std=gnu99 -g -Oz -c 
CSECFL= -fPIC -I -L 
CFLAG3= -shared
RM= /bin/rm -f
OBJ= math.o my*.o
SO= libmymath.so

all: math my_add my_mul 

math: math.c
    $(CC) $(CFLAGS) $@.c $(CSECFL)

my_add: my_add.c
    $(CC) $(CFLAGS) $@.c $(CSECFL)

my_mul: my_mul.c
    $(CC) $(CFLAGS) $@.c $(CSECFL)

simplemath: $(OBJ)
    $(CC) $(OBJ) -o $@ 

simplemath.o: $(OBJ)
    $(LD) $(OBJ) -o $@

lib1: my_add.o
    $(CC) $(CFLAG3) my_add.o -o $(SO)

lib2: $(OBJ)
    $(CC) $(CFLAG3) my_mul.o -o $(SO)

lib3: $(OBJ)
    $(CC) $(CFLAG3) math.o -o $(SO)

simpleone: $(OBJ)
    $(LD) -L./ -l:libmymath.so $@

clean:
    $(RM) *.o simplemath* *.t $(SO)

最佳答案

您需要将对象 (*.o) 链接到静态可执行文件,而不是共享库 (.so)。so 可以通过运行时动态链接器或通过 dlopen() 调用打开。

关于c - 将 .so 文件链接成可执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717486/

相关文章:

c - 什么是 C 中好的开源 B 树实现?

c - 循环展开和优化

c - 使用 scanf 或 gets 进行输入的运行时异常

c++ - 制作 OpenCV 时出错

c - 数组 boolean 值如何将 Char 条目与 true 或 false 相关联?

c - make : 'file' is up to date, 后面什么都不做

c - 在 Debian 上不用 IDE 编程 STM32F4x

ios - 体系结构 x86_64 : "_CBCentralManagerOptionShowPowerAlertKey", 的 undefined symbol 在 React Native 中导入 Appodeal

c++ - 在 Eclipse 中设置构建输出目录 - c++

c++ - 使用 opencv 时找不到 lopencv_core