以下代码可以正常编译:
\n#include <cstddef>\n\nstruct A {\n char a;\n static constexpr int off(void) { return offsetof(A, a); }\n static constexpr int (*off_p)(void) = off;\n};\nRun Code Online (Sandbox Code Playgroud)\n以下看似相似的代码\n仅使用 lambda 简称,但无法编译:
\n#include <cstddef>\n\nstruct A {\n char a;\n static constexpr int (*off_p)(void) =\n [](void) static constexpr ->int { return offsetof(A, a); };\n};\nRun Code Online (Sandbox Code Playgroud)\n$ g++ -std=c++23 bad.cpp \nIn file included from /usr/include/c++/13/cstddef:50,\n from bad.cpp:1:\nbad.cpp: In static member function \xe2\x80\x98A::<lambda()> static\xe2\x80\x99:\nbad.cpp:5:74: error: invalid use of incomplete type \xe2\x80\x98struct A\xe2\x80\x99\nRun Code Online (Sandbox Code Playgroud)\n所以基本上我有两个不同的问题,因为我不明白这里发生了什么。
\n考虑这个例子:
\nint foo(void);\nextern "C" int foo(void);\n\nint main()\n{\n return foo();\n}\nRun Code Online (Sandbox Code Playgroud)\n它出错了:
\n$ g++ -c main.cpp\nmain.cpp:2:16: error: conflicting declaration of \xe2\x80\x98int foo()\xe2\x80\x99 with \xe2\x80\x98C\xe2\x80\x99 linkage\n 2 | extern "C" int foo(void);\n | ^~~\nmain.cpp:1:5: note: previous declaration with \xe2\x80\x98C++\xe2\x80\x99 linkage\n 1 | int foo(void);\n | ^~~\nRun Code Online (Sandbox Code Playgroud)\n这完全没问题。
\n但是让我们交换前两行:
\nextern "C" int foo(void);\nint foo(void);\n\nint main()\n{\n return foo();\n}\nRun Code Online (Sandbox Code Playgroud)\n现在它编译时没有任何错误,\n但是选择了 C 链接,即使\n最后找到了 C++ 链接。
\n问题:
\n