c++
当我尝试编译以下代码时,我收到一个冲突的声明错误:
#include <iostream>
using namespace std;
typedef uint_least64_t uint;
int main() {
uint i = -1;
cout << i << endl;
}
错误:
main.cpp:5:24: error: conflicting declaration ‘typedef uint_least64_t uint’
typedef uint_least64_t uint;
^~~~
In file included from /usr/include/stdlib.h:275:0,
from /usr/include/c++/6/cstdlib:75,
from /usr/include/c++/6/ext/string_conversions.h:41,
from /usr/include/c++/6/bits/basic_string.h:5417,
from /usr/include/c++/6/string:52,
from /usr/include/c++/6/bits/locale_classes.h:40,
from /usr/include/c++/6/bits/ios_base.h:41,
from /usr/include/c++/6/ios:42,
from /usr/include/c++/6/ostream:38,
from /usr/include/c++/6/iostream:39,
from main.cpp:1:
/usr/include/x86_64-linux-gnu/sys/types.h:152:22: note: previous declaration as ‘typedef unsigned int uint’
typedef unsigned int uint;
^~~~
我假设冲突声明错误是因为语言中某处已经存在uint
的类型声明,并且我相信该类型uint_least32_t
,因为:
#include <iostream>
using namespace std;
int main() {
uint i = -1;
cout << i << endl;
}
返回一个整数值,该值为 (2^32)-1。因此,c++
是否有可能将uint
重新定义为uint_least64_t
。
从错误消息中可以看出,在您的平台上,<iostream>
拉入<string>
,拉入<cstdlib>
,拉入<stdlib.h>
,拉入<sys/types.h>
。
查看源代码,我们可以看到<sys/types.h>
这样做:
#ifdef __USE_MISC
/* Old compatibility names for C types. */
typedef unsigned long int ulong;
typedef unsigned short int ushort;
typedef unsigned int uint;
#endif
#ifdef __USE_MISC
卫士是feature_test_macros
系统的一部分。 如果您请求_DEFAULT_SOURCE
,则会在内部设置__USE_MISC
(如果您不请求任何其他请求,也会设置)。
因此,您应该能够通过使用 -ansi
或-std=...
选项之一进行编译来绕过问题(例如 -std=c++11
)。
uint
不是标准C++的一部分。
很可能是代码库中的某些内容引入了它,甚至是编译器附带的C++标准库。您可能很幸运,并且库引入了std::uint
并且当您编写污染语句时,您正在将其引入全局命名空间using namespace std;
。
可悲的是,一旦引入类型,您就无法取消typedef
类型或隐藏class
。
因此,您只需要使用不同的符号即可。
您不能重新定义 typedef 符号,并且必须使用不同的(未使用的)符号。
如果你想使用相同的符号,你可以把它包装在命名空间中,如这篇文章所述:使用 typedef'd uint 会导致错误,而"无符号 int"不会......?