← 返回日报
精读 预计 1 分钟

neither gcc nor clang are compliant with standard c++

摘要

正文说明 C++ 标准明确规定不同语言链接(C++、C 等)的函数类型即使其他相同也是不同类型,目的是支持可能的调用约定差异;但 GCC 和 Clang 不保存语言链接信息,因此不同链接的函数类型可被视为相同;这会造成对带函数指针参数的函数重载时出现本不应有的编译失败(违反 ODR);作者认为问题源于标准而非编译器,标准应修改为实现定义,且编译器因 mangled name 的 ABI 兼容性无法改变行为,同时多数平台上 C 与 C++ 调用约定相同。

荐读理由

这篇文章用具体代码示例和 ABI 理由论证 C++ 标准在语言链接上的要求不切实际,GCC/Clang 不实现是正确选择,你据此能重新判断混合 C/C++ 代码的合规风险和重载行为

原文

neither gcc nor clang are compliant with standard c++

2026-07-08

in c++, function types have a "language linkage" associated with them: this is either "C++", "C", or some other implementation-defined language. and the standard very explicitly states that Two function types with different language linkages are distinct types even if they are otherwise identical. the idea is that some implementations may have different calling conventions for c++ functions than for c functions, so they can't be intermixed

gcc and clang however, just, don't store language linkage information with the type. so two functions with different language linkages can be identical:

#include <type_traits>
extern "C" using c_func = void ();
// this static assertion should fail, but it doesn't
static_assert(std::is_same<c_func, void ()>::value);

this can also cause erroneous compilation failures when overloading a function which takes in a function pointer parameter:

extern "C" using c_func = void ();
void f(c_func *) {}
void f(void (*)()) {}

the above code should compile, but gcc and clang both think that the parameter lists are identical and thus this violates the one definition rule

IMO the blame here doesn't lie on gcc or clang; it lies on the standard. that is, the standard is wrong and should be updated to make this implementation-defined. gcc and clang can't change their behavior because that would be a breaking ABI change (extern "C" function types in mangled names would be encoded differently). and they have no reason to make this change: the calling conventions for c and c++ are identical on, as far as i can tell, pretty much every platform

Lobsters · 1 赞 · 0 评 讨论 → 阅读原文 →

这条对你有帮助吗?