gpt4 book ai didi

c - 为什么对匿名结构的命名引用,下面描述的习语需要 -fms-extensions 由 clang/gcc 编译

转载 作者:太空狗 更新时间:2023-10-29 15:02:21 28 4
gpt4 key购买 nike

我编写了以下代码来玩转《21 世纪 C》一书中描述的匿名结构的特定 C11 习语

#include <stdio.h>
#include <math.h>


typedef struct Price {
double close;
double high;
double low;
} Price;

typedef struct OLHC {
union { //union allows the dual benefits of the seamless anon. struct and code-reuse
struct Price; //an anonymous struct but not explicitly re-defined
Price p;
};
double open;
} OHLC;


double range(Price p){ //behaviour defined for struct Price
return(p.high - p.low);
}

double travelRange(OHLC p){ //re-uses behaviour defined for struct Price
return (fabs(p.open - p.low) + range(p.p) + fabs(p.high - p.close));
}

int main(){
OHLC msft={.close=33.4, //seamless access to members
.open=32.1,
.high=35.5,
.low=30.23};
printf("Today's travel Range for MSFT was %f\n",travelRange(msft));
}

我可以使用 gcc48 或 gcc49 如下所示在没有警告的情况下编译它:

gcc-4.9  -std=c11 -fms-extensions -lm -o c11 c11.c

我还可以让它在我的 OS X mavericks macbook 上编译和运行,但有一个警告:

cc -std=c11 -fms-extensions -lm -o c11 c11.c

警告是:

c11.c:19:5: warning: anonymous structs are a Microsoft extension[-Wmicrosoft]

是否有任何版本的 gcc 或 clang 可以仅使用 std=c11 标志编译此文件而不会出现警告。匿名结构/union 是 C11 标准的一部分,只是尚未实现,还是它们如上所用不符合标准?

编辑:只是为了澄清上面的代码旨在允许重用为基本结构编写的代码,但同时获得无缝访问包含原始结构的派生结构的所有成员的好处匿名。这是通过匿名结构及其相应的命名类型的 union 来实现的。太糟糕了,这不合规,因为我认为这是一个非常好的小习惯用法。

最佳答案

typedef struct OLHC {
union {
struct Price;
Price p;
};
double open;
} OHLC;

不是 C11。它是带有扩展名的 C,并且只允许在带有 -fms-extensions 选项的 gcc 中使用。

C11 具有匿名结构和 union ,但是:

    struct Price;

在你的 struct OLHC 中不允许作为 C11 匿名结构的一部分。

Is there any version of gcc or clang which will compile this file with just the std=c11 flag without warnings.

不,C 至少需要一个警告。

关于c - 为什么对匿名结构的命名引用,下面描述的习语需要 -fms-extensions 由 clang/gcc 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20108938/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com