使用MinGW使用一些未定义的引用编译为.dll [英] Compile to .dll with some undefined references with MinGW
问题描述
我在某处听说所有Windows .DLL 必须都包含其所引用的每个符号的定义,因此像这样的.DLL文件将永远不会编译,因为它没有实现 bar()
.
I heard somewhere that all Windows .DLLs must contain definitions for every symbol it references, so a .DLL file like this would never compile since it doesn't implement bar()
.
void bar();
__declspec(dllexport)
void foo() {
bar();
}
我认为类比是.DLL本质上是具有不同入口点的可执行文件,因此必须定义所有引用,例如可执行文件.
I think the analogy is that .DLLs are essentially executables with a different entry point, so they have to have all referenced defined, like an executable.
但是在Unix环境中,我可以毫无问题地将其编译为.so文件.然后,我可以从主机应用程序中使用 dlopen(path,RTLD_NOW | RTLD_GLOBAL);
来加载库并将主机的符号与库的符号合并.如果主机定义了 bar()
,则库将简单地调用该函数.
But in a Unix environment, I can compile this to a .so file with no problem. I can then use dlopen(path, RTLD_NOW | RTLD_GLOBAL);
from the host application to load the library and merge the host's symbols with the library's. If the host defines bar()
, the library will simply call that function.
我不能只将所有内容重新定义到.DLL文件中,因为在我的应用程序中,库使用了来自主机的数千个符号.使用MinGW或可能的Visual C ++,实际上没有办法通过将主机中的符号保留为未定义状态而将其保留在.DLL中,并在加载时将其合并吗?我也不想在.DLL中设置成千上万个回调函数,因为使用C ++方法很难做到这一点.
I can't just re-define everything into the .DLL file, because in my application the library uses thousands of symbols from the host. Using MinGW or possibly Visual C++, is there really no way to use a symbol from the host by leaving it undefined in the .DLL and merging it when loaded? I don't want to set thousands of callback functions in the .DLL either, because that gets difficult with C++ methods.
推荐答案
我想出了如何使用MinGW做到这一点.
I figured out how to do it with MinGW.
通常,当链接DLL文件(例如 plugin.dll
)时,您将符号列表导出到 libplugin.a
,但是在这种情况下,我实际上想将符号从主机可执行文件 host.exe
导出到 libhost.a
.
Usually, when linking DLL files (e.g. plugin.dll
), you export a list of symbols to libplugin.a
, but in this case, I actually want to export the symbols from the host executable host.exe
to libhost.a
.
x86_64-w64-mingw32-g ++ -o host.exe host.cpp -Wl,-out-implib,libhost.a
这将生成符号列表,您可以在构建插件时将其链接到该列表.
This generates the symbol list, which you can link to when building your plugin.
x86_64-w64-mingw32-g ++ -shared -o plugin.dll plugin.cpp -L.-lhost
这将使用 libhost.a
文件(在当前目录."中)构建DLL.
This builds the DLL using the libhost.a
file (in the current directory ".").
现在,用 __ declspec(dllexport)
填充主机代码有点烦人,因此您可以添加-export-all-symbols
链接器标志.出于某种原因,执行此操作后似乎都不需要 _declspec(dllimport)
属性,但是我不知道为什么.因此,您可以使用
Now, it's a bit annoying to fill your host code with __declspec(dllexport)
, so you can add the --export-all-symbols
linker flag.
And for some reason, it doesn't seem to require _declspec(dllimport)
attributes either after doing this, but I don't know why.
So, you can compile the host with
x86_64-w64-mingw32-g ++ -o host.exe host.cpp -Wl,-export-all-symbols,-out-implib,libhost.a
这篇关于使用MinGW使用一些未定义的引用编译为.dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!