1

我有以下关于在 gcc 4.4.6 中编译好的结构的来源:

struct st1
{
    char name[12];
    int heartbeat ;
    double price ;
    int iFlag ;
} ;

struct st2  {
    struct st1 ;
    char pad[64 - sizeof(struct st1)] ;
} __attribute__((aligned(64))) ;

int main (void)
{
    printf("length of struct st2=(%d)\n",sizeof(struct st2) ) ;
}


gcc -fms-extensions test1.c -o test1.exe

./test1.exe ===> length of struct st2=(64)

我将 test1.c 复制到 test1.cpp 并尝试编译为:

g++ -fms-extensions test1.cpp -o test1.exe 

然后我得到了:

test1.cpp:23: 错误: sizeof 对不完整类型 st2::st1 的无效应用

我知道这个错误显示 char pad[64 - sizeof(struct st1)] ;在 g++ 中不起作用,虽然它在 gcc 中起作用,如果我喜欢它在 g++ 中起作用,我该怎么办?

4

2 回答 2

3

在您的结构 st2 中:

struct st1 ;

这是 a 的前向声明struct st1。在这里,您基本上是在对您的编译器说:“嘿,在(因此是)struct st1的命名空间中有 a ,但我不会给您它的属性!” 由于您没有提供其属性,编译器将引发“不完整类型”错误:它无法知道此类型的大小,因此无法解析您的.struct st2st2::st1sizeof

如果你想在你的 中有一个你的实例struct st1struct st2你应该写:

struct st1 my_variable_name;

这将有效地struct st1在您的struct st2.

如果您不想要您的实例struct st1struct st2只需删除此行 - 您的编译器已经知道struct st1, 因为它已在上面声明。

于 2013-04-02T04:42:37.043 回答
0

删除“结构”并使用 sizeof(st1)。通过添加“struct”,您是在告诉编译器在 st2 的范围内定义一个新的 struct st1。因此为什么它说“st2::st1”。

于 2013-04-02T04:43:48.133 回答