【问题标题】:What causes error "expected a string literal, but found a user-defined string literal instead" when using 'extern "C"'?使用'extern“C”'时,是什么导致错误“预期字符串文字,但找到了用户定义的字符串文字”?
【发布时间】:2023-03-07 18:03:01
【问题描述】:

我有包含这些声明的代码:

class IRealNetDll;

extern "C"__declspec(dllexport)
IRealNetDll * CreateRealInstance(int ilicence);

这可以在 Win7 上使用 Visual Studio 2012 正确构建。

但在 Windows 10 上的 VS 2015、2017 上,这一行:

extern "C"__declspec(dllexport)

结果:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C3690: expected a string literal, but found a user-defined string literal instead
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2146: syntax error: missing ';' before identifier 'IRealNetDll'

为什么会出现这个错误,为什么只在较新的编译器上出现,我该如何防止它?

【问题讨论】:

  • 与您的问题无关,但以下划线开头并后跟大写字母的符号(例如_IRealNetDll)在任何地方都保留。请参阅What are the rules about using an underscore in a C++ identifier? 了解更多信息
  • 注意你的间距(或者更确切地说是事物之间的空间缺乏)。
  • @πάνταῥεῖ 错误非常extern "C"__declspec(dllexport)部分相关。错误消息的“用户定义的字符串文字”部分泄露了它。

标签: c++ visual-studio visual-c++ visual-studio-2012 windows-10


【解决方案1】:

当引入用户定义的文字时,它对语言造成了微小的破坏性变化。字符串文字现在需要用空格与后面的标识符分开,否则标识符将被解析为用户定义的文字运算符:

  • "C"__declspec
    

    一个标记,理解为使用__declspec 转换的用户定义文字。

  • "C" __declspec
    

    两个标记 - 字符串文字 "C" 和标识符 __declspec

您需要添加一个空格来分隔您的标记。

【讨论】:

    【解决方案2】:

    代替

    extern "C"__declspec(dllexport)
    IRealNetDll * CreateRealInstance(int ilicence);
    

    你应该写

    extern "C"
    {
    __declspec(dllexport) IRealNetDll * CreateRealInstance(int ilicence);
    }
    

    【讨论】:

    • 虽然您提出的解决方案应该可以工作,但这并不是因为花括号 {}。还有一个更简单的解决方案。
    • 你说得对,我认为问题是“C”之后缺少一个空格。但我相信使用不带花括号的 extern "C" 会令人困惑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 2020-01-31
    • 2020-11-01
    • 2015-09-08
    • 2018-10-19
    相关资源
    最近更新 更多