使用mingw在Windows下生成动态库时,未定义的符号错误,但Linux没有
我有一个名为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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
错误是有道理的:您有
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 thehello()
function (e.g. withgcc -o libhelloworld.exe hello_world.o
).The solution is define the actual body for
hello()
, either inhelloworld.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).