且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows和Linux上的C ++ [[gnu :: visibility("default")]]与__declspec(dllexport)

更新时间:2023-02-20 10:17:31

符号可见性与dllexport完全不同-主要原因是当您在Windows中的mingw/cygwin下编译.dll时,默认链接器的行为是选项-export-all-symbols-即默认情况下它将自动从您的.dll导出一切.

Symbol visibility is subtly different from dllexport - and the primary reason is that when you compile a .dll in Windows under mingw/cygwin, the default behaviour of the linker is the option -export-all-symbols - i.e. it will auto-export everything from your .dll by default.

您可以通过使用.def文件或将__declspec((dllexport))__attribute((dllexport))放在 any 例程中来更改此行为(即,如果您指定要导出单个符号,则仅导出声明为已导出的符号).如果您的库中有很多符号,则可以在dll加载时显着提高性能.

You can change this behaviour by either using a .def file or putting either __declspec((dllexport)) or __attribute((dllexport)) on any routine (i.e. if you specify that a single symbol is to be exported then only the symbols that are declared exported are exported). This can have a significant performance improvement at dll load time if there are a lot of symbols in your library.

如果要使用等效的C++属性,请使用[[gnu::dllexport]]

If you want to use the equivalent C++ attribute, then you use [[gnu::dllexport]]

是的,请使用dllexport阻止.dll导出世界.

So yes, use dllexport to keep your .dll from exporting the world.

以类似的方式,您可以使用[[gnu:dllimport]]导入外部例程.

In a similar manner you can use [[gnu:dllimport]] for importing external routines.

在阅读文档时要小心;它的实际含义是,当您使用dllexport属性时,除非被覆盖,否则它还会触发visibility:default行为.

Careful while reading the documentation; what it actually says is that when you use the dllexport attribute, it also triggers the visibility:default behaviour unless it's overridden.