Home > Net >  How to link to shared object library in msys2?
How to link to shared object library in msys2?

Time:11-01

I have some c code in msys2 that I am trying to link dynamically to show how a dynamic link library works.

In linux, showing the call is no problem. stepping in gdb, we can watch the call go through the jump vector, eventually landing in the desired function.

But in msys2, they wanted to eliminated dlls and all the libraries I can find are .dll.a, I think they are really static libraries.

I build a trivial little function like this:

#include <cstdint>
extern "C" {
  uint64_t f(uint64_t a, uint64_t b) {
    return a   b;
  }
}

compiling in the makefile with:

g   -g -fPIC -c lib1.cc
g   -g -shared lib1.o -o libtest1.so

When I run the file utility, it says that:

libtest1.so: PE32  executable (DLL) (console) x86-64, for MS Windows

When I compile the code using it:

g   -g main.cc -ltest1 -o prog

The error is -ltest1 no such file or directory.

CodePudding user response:

MinGW uses the .dll extension for shared libraries, not .so.

lib??.dll.a is an import library, a shim that will load the corresponding lib??.dll at runtime.

At some point in time, you couldn't link .dlls directly, and had to link .dll.as instead. The modern MinGW can link .dlls directly, so you shouldn't need to use import libraries anymore.

-ltest1 no such file or directory

Wouldn't you get the same error on Linux? You have to specify the library search path with -L. -ltest1 needs either libtest1.a or libtest1.dll.a or libtest1.dll (perhaps some other variants are checked too).

CodePudding user response:

The reason your linker cannot find the library is because your current working directory is not in the search path for libraries. Add -L. to your linking command.

It is untrue that MSYS2 "wanted to eliminate DLLs". Just run ls /mingw64/bin/*.dll and you will see plenty of DLLs (assuming you have some MINGW64 packages installed). The .dll.a files used for linking are called import libraries.

  • Related