gpt4 book ai didi

c - 在 cygwin 中与 gcc 动态链接时 undefined reference

转载 作者:太空狗 更新时间:2023-10-29 14:57:54 25 4
gpt4 key购买 nike

(这是 Cygwin 上的 gcc 3.3.1(长话短说——怪 NIST)。)

我用 gcc -c -fPIC ... 编译了一些源文件以获得 .o 文件。

然后我做了:

$ gcc -shared -o foo.dll foo.o bar.o

但是当我去使用它的时候:

$ gcc -o usefoo.exe usefoo.o -L. -lfoo
usefoo.o:usefoo.cpp:(.text+0x2e0): undefined reference to `_get_template_size'
collect2: ld returned 1 exit status

但是,如果使用相同的 .o 文件,我改为:

$ ar rcs libfoo-static.a foo.o bar.o

链接成功:

$ gcc -o foo.exe foo.o -L. -lfoo-static

令我感到奇怪的是,正如您在下面看到的那样,有问题的引用同时存在于 .a 和 .dll 中。那么,为什么在链接 .dll 时出错?

在共享库中找到引用:

$ nm foo.dll|grep get_template
1001b262 T _get_template_size

而且它也在静态库中:

$ nm libfoo-static.a |grep get_template
00000352 T _get_template_size

这里是对要使用该函数的文件中生成的符号的引用:

$ nm usefoo.o
00000000 b .bss
00000000 d .data
00000000 t .text
0000012c T __Z12ErrorMessagei
U ___main
U __alloca
U _atoi
U _get_template_size
0000026c T _main
U _printf

已更新以解决 Marco 的回答

有趣/烦人的是,当我尝试为此做一个最小的测试示例时,我无法实现它(尽管它每次都发生在真实的事情上):

func1.h:

#ifndef FUNC1_H
#define FUNC1_H

int func1(int i);

#endif

func1.c:

#include "func1.h"

int func1(int i) {
return 2*i;
}

usefunc.c:

#include <stdio.h>
#include "func1.h"

int main() {
printf("%d\n", func1(10));
}

然后:

$ rm *.o *.dll *.a

$ gcc -fPIC -I. -c func1.c usefunc.c

$ gcc -shared -o func.dll func1.o

$ gcc -L. -o usefunc.exe usefunc.o -lfunc

$ ./usefunc.exe
20

最佳答案

我在 Cygwin 网页上找到了答案(因为它解决了我的链接问题):http://cygwin.com/cygwin-ug-net/dll.html

我最终要做的是创建共享库并像这样做最后的链接:

$ gcc -shared -o cygfoo.dll \
-Wl,--out-implib=libfoo.dll.a \
-Wl,--export-all-symbols \
-Wl,--enable-auto-import \
-Wl,--whole-archive *.o \
-Wl,--no-whole-archive

$ gcc -L. -o usefoo.exe usefoo.o -lfoo

但我仍然很想知道为什么我不必为我的简单测试执行此操作。

关于c - 在 cygwin 中与 gcc 动态链接时 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com