繁体   English   中英

gcc-如何在结构定义中组合__attribute __((dllexport))和[[nodiscard]]?

[英]gcc - How to combine __attribute__((dllexport)) and [[nodiscard]] in a struct definition?

我有一个标有C ++ 17的[[nodiscard]]属性的结构。 定义如下:

struct [[nodiscard]] MyObject final
{
    explicit MyObject(int id);
    ~MyObject();

    MyObject(const MyObject&) = delete;
    MyObject& operator=(const MyObject&) = delete;

    int id;
};

现在,我想从动态库中导出它。

在MSVC上,语法struct __declspec(dllexport) [[nodiscard]] MyObject final可以正常工作。

但是GCC无法同时编译struct __attribute__((dllexport)) [[nodiscard]] MyObject finalstruct [[nodiscard]] __attribute__((dllexport)) MyObject final :编译器无法处理这种语法。

语法__attribute__((dllexport)) struct [[nodiscard]] MyObject final编译,但似乎没有执行我想要的操作,因为它会产生以下警告:

:1:49:警告:“ struct MyObject”的声明中忽略了属性[-Wattributes]

 1 | __attribute__((dllexport)) struct [[nodiscard]] MyObject final | ^~~~~~~~ 

:1:49:注意:“ struct MyObject”的属性必须跟随“ struct”关键字

那么,如何从GCC上的动态库中导出[[nodiscard]]结构?

尝试使用C ++属性而不是使用__attribute__

struct [[gnu::dllexport]] [[nodiscard]] MyObject final

并且也使用定义来与MSVC一起使用

所有这些都适用于dllexportdllimport

这似乎是GCC解析器中的错误。

Clang 设法解析 struct __attribute__((dllexport)) [[nodiscard]] MyObject ...版本。

正如@Artyer所指出的那样 ,GCC(和Clang)支持dllexport - [[gnu::dllexport]]的C ++语法。

还应该注意的是,Windows上的GCC(MinGW)支持__declspec(dllexport)以与Visual C ++兼容,并且实际上可以正确解析class __declspec(dllexport) [[nodiscard]] Test ... (已通过GCC class __declspec(dllexport) [[nodiscard]] Test ... )。


以上所有条件均假定您正在针对Windows进行编译,其中dllexport实际上意味着某些东西。 在其他平台上,编译器只会忽略它(通常会发出警告)。

在Linux上,应该使用-fvisibility=hidden隐藏所有符号,但属性visibility("default")选择的符号除外。 没有“导入”选项-在构建和使用库时都使用"default" 在Linux上导出类时,可以将不需要导出的任何内容标记为visibility("hidden")以覆盖该类的属性。

GCC和Clang支持visibility两种语法: __attribute__((visibility("default")))[[gnu::visibility("default")]]

这里可以找到有关GCC可见性的更多信息。

我不确定从共享库中导出符号在MacOS上如何工作(也许与Linux上的相同?)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM