C++代码编译失败,错误"长类型名称"无效

C++ code fails to compile with error 'long type-name' is invalid

本文关键字:类型 无效 错误 代码 编译 失败 C++      更新时间:2023-10-16

我更喜欢避免使用typedef,而更喜欢使用using,但我偶然发现了必须使用它的情况,因为thrift(0.9.3版本)输出的代码使用了typedef。错误的最小实例出现在以下代码中

#include <iostream>
using namespace std;
typedef int64_t long;
typedef int32_t int;
int main() {
cout << "Hello world " << endl;
return 0;
}

我得到的错误是

test.cpp:4:17: error: 'long type-name' is invalid
typedef int64_t long;
^
test.cpp:4:1: error: typedef requires a name [-Werror,-Wmissing-declarations]
typedef int64_t long;
^~~~~~~~~~~~~~~~~~~~
test.cpp:5:17: error: cannot combine with previous 'type-name' declaration specifier
typedef int32_t int;
^
test.cpp:5:1: error: typedef requires a name [-Werror,-Wmissing-declarations]
typedef int32_t int;
^~~~~~~~~~~~~~~~~~~
4 errors generated.

我从g++ --version得到的输出是

Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.4.0
Thread model: posix

有人能帮我解决这个错误吗?

long是c++中的一个关键字,因此不能创建名称为long的类型。请参阅列表。

但问题在于Thrift生成的代码。我用Thrift做了一些实验,我可以通过在官方tutorial.thrift文件中添加这一行来重现这个问题:

typedef i64 long

显然Thrift不会检查这是否会编译。因此,您需要确保您的typedef适用于所有可能的语言。

应该是

typedef long int64_t;
typedef int int32_t;

Typedef的工作方式类似于变量声明,只是前面有typedef