使用mingw在Windows下生成动态库时,未定义的符号错误,但Linux没有

发布于 2025-02-12 11:14:06 字数 710 浏览 0 评论 0原文

我有一个名为helloworld.c的文件,该文件取决于一个称为libhello.dll的外部动态库。

/* helloworld.c */
#include <stdio.h>

void hello(void);

int main() {
    hello();
    return 0;
}

现在,我想将helloworld.c编译到动态库中。我在Windows下安装mingw,然后使用命令:

gcc -shared -fpic -o libhelloworld.dll hello_world.c

发生了一些可怕的事情,命令报告了一个错误:

undefined reference to `hello'
collect2.exe: error: ld returned 1 exit status

我必须明确指定依赖的库至编译:

gcc -shared -fPIC -o libhelloworld.dll hello_world.c -L. -lhello

这是非常愚蠢的,这在Linux中不会发生,在Linux下生成动态库时,允许不确定的符号,为什么不在Windows下。

有什么方法可以使Windows像Linux一样行为,而无需使用-L和-L在生成动态库时指定动态库的路径和名称?例如添加一些编译选项等等

I have a file called helloworld.c, which depends on an external dynamic library called libhello.dll.

/* helloworld.c */
#include <stdio.h>

void hello(void);

int main() {
    hello();
    return 0;
}

Now I want to compile helloworld.c into a dynamic library. I install mingw under windows, then I use the command:

gcc -shared -fPIC -o libhelloworld.dll hello_world.c

Something terrible happened, the command reported an error:

undefined reference to `hello'
collect2.exe: error: ld returned 1 exit status

I must explicitly specify the dependent library to compile:

gcc -shared -fPIC -o libhelloworld.dll hello_world.c -L. -lhello

This is very stupid, this doesn't happen in linux, undefined symbols are allowed when generating dynamic libraries under linux, why not under windows.

Is there any way to make windows behave like linux, without using -L and -l to specify the path and name of the dynamic library when generating the dynamic library? Such as adding some compile options and so on

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原来是傀儡 2025-02-19 11:14:06

错误是有道理的:您有void Hello(void);的正向声明,但没有对该功能的实际实现。

因此,编译器将工作(例如gcc -c -c -o hello_world.o hello_world.c),但是链接器不知道在哪里可以找到Hello()hello()函数(例如,使用GCC -O libhelloworld.exe hello_world.o)。

该解决方案是为hello()的实际主体定义的,要么在helloworld.c中,或者在单独链接到同一输出文件,或通过库(.a通过-L flag链接的文件)。

The error makes sense: you have a forward declaration for void hello(void); but no actual implementation of that function.

So the compiler will work (e.g. with gcc -c -o hello_world.o hello_world.c), but the linker doesn't know where to find the hello() function (e.g. with gcc -o libhelloworld.exe hello_world.o).

The solution is define the actual body for hello(), either in helloworld.c, or in a seperate .c file that is compiled and linked into the same output file, or via a library (.a file linked via -l flag).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文