来自 C++11 草案,7.5(第 1 段):
Two function types with different language linkages are distinct types even if they are otherwise identical.
所以我可以根据语言链接进行重载:
extern "C" typedef void (*c_function)();
typedef void (*cpp_function)();
void call_fun(c_function f)
{
}
void call_fun(cpp_function f)
{
}
extern "C" void my_c()
{
}
void my_cpp()
{
}
int main()
{
call_fun(my_c);
call_fun(my_cpp);
}
但是,对于 GCC 4.7.1,此示例代码会给出错误消息:
test.cpp: In function 'void call_fun(cpp_function)':
test.cpp:7:6: error: redefinition of 'void call_fun(cpp_function)'
test.cpp:4:6: error: 'void call_fun(c_function)' previously defined here
还有 CLang++:
test.cpp:7:6: error: redefinition of 'call_fun'
void call_fun(cpp_function f)
^
test.cpp:4:6: note: previous definition is here
void call_fun(c_function f)
^
现在问题:
我对标准的理解正确吗?这段代码有效吗?
有人知道这些是编译器中的错误还是出于兼容性目的而故意这样做?
最佳答案
代码显然是有效的。 G++(和许多其他编译器)是一个 将链接集成到类型中有点松懈(委婉地说)。
关于c++ - extern "C"函数是单独的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12474351/