I have a file mylib.c
with the following content:
extern void some_function(void);
int add(int a, int b) {
some_function();
return a+b;
}
I want to create a shared library from it. The function some_function
should be linked dynamically by the consumer of the shared library. So while building the shared library, the symbol remains unresolved.
When I use gcc on Ubuntu via...
gcc mylib.c -o libmylib.so -shared
...the build succeeds.
However, I also need to cross-build the library for Windows. I am using mingw-w64 for this:
sudo apt install -y mingw-w64
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared
Now, I get this error:
/usr/bin/x86_64-w64-mingw32-ld: /tmp/ccWlwvfS.o:mylib.c:(.text+0xf): undefined reference to `some_function'
collect2: error: ld returned 1 exit status
After some research, I tried out various options to fix this. Below are some of them:
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared -Wl,--no-undefined
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared -Wl,-u,some_function
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared -Wl,-u,_some_function
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared -Wl,-U,some_function
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared -Wl,-U,_some_function
x86_64-w64-mingw32-gcc mylib.c -o mylib.dll -shared -Wl,--unresolved-symbols=ignore-all
None of them work, unfortunately.
How do I have to configure the linker so that it works? Or is there another workaround to get a DLL with link-time-undefined symbols from a Linux host?
When building Windows shared libraries (DLL files) with MinGW-w64 you should ether link specifying a .def
file used to list the symbols you will be exporting, or use __declspec(dllexport)
/ __declspec(dllimport)
on your exported/imported functions (the latter is most commonly used).
For a minimal example on how to do this please see: https://github.com/brechtsanders/ci-test