考虑以下翻译单元:
extern "C" int x = 1;
我知道 C-mangling 一个 int
没有多大意义;并且 int x = 1
已经 guarantees外部链接,但这应该有效。它是做什么的;问题是,GCC 会警告使用它,而 clang 不会:See this on GodBolt .
- 哪个编译器“正确”?
- 强烈建议您避免使用此类代码?
最佳答案
根据 [dcl.link.2] 的标准
Linkage between C++ and non-C++ code fragments can be achieved using a linkage-specification:
linkage-specification:
extern string-literal { declaration-seq }
extern string-literal declaration
括号括起来和作为单个声明的前缀都是有效的。
哪个编译器是正确的?我会说两者,因为他们都接受代码并用它做正确的事情。
GCC 的警告只是一个警告。这是与“命名参数未在任何地方使用”相同类型的警告:有关异常情况但不影响程序行为的信息。
关于c++ - 一个变量的一行 extern "C"- 合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72452368/