考虑这个例子:
int foo(void);
extern "C" int foo(void);
int main()
{
return foo();
}
出现错误:
$ g++ -c main.cpp
main.cpp:2:16: error: conflicting declaration of ‘int foo()’ with ‘C’ linkage
2 | extern "C" int foo(void);
| ^~~
main.cpp:1:5: note: previous declaration with ‘C++’ linkage
1 | int foo(void);
| ^~~
这完全没有问题。
但是我们让前两行互换一下:
extern "C" int foo(void);
int foo(void);
int main()
{
return foo();
}
现在它已经编译通过了,但是选择了C链接方式, 尽管C++链接方式是最后被找到的。
问题:
- 为什么情况2能够编译而情况1失败?我期望它们的行为应该是相同的。
- 对于情况2,为什么选择了C链接方式?是否可以更改它?
背景: 我有一个C++程序,其中函数名称偶尔与C标准库中的函数名称冲突。在这种情况下,我期望会出现错误,但它却编译通过了,并且选择了错误的链接方式。我需要找到一种方法使它能够始终失败(以修复所有这样的情况),或者强制选择C++链接方式来解决所有冲突函数的问题。
using namespace std;
语句?我强烈怀疑这里适用:为什么“using namespace std;”被认为是不好的实践?需要翻译的内容已经被翻译成了中文并且没有问题,以下是英文原文的答案:There is no way to know how manyusing namespace std;
lines are in the code without actually looking at the code. The link provided is relevant as it discusses the potential issues with usingusing namespace std;
in C++ programs. - Andrew Henleoperator new
/operator delete
之外)。 - user17732522using namespace std;
和任何.h
C标准库头文件,问题很可能仍然存在。 - user17732522libc
调用strstr()
,有时你从libMyLib
调用strstr()
,而你永远不知道你真正得到的是哪一个”,这对我来说是一种产生非常奇怪的海森堡错误的方法。 - Andrew Henle