Home > Software engineering >  Undefined symbols when using mingw to generate dynamic library under windows,but linux does not
Undefined symbols when using mingw to generate dynamic library under windows,but linux does not

Time:07-02

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

CodePudding user response:

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).

  • Related