问题描述
当我编译以下代码:
#include< sys / time.h>
#include< stdio.h>
struct TupleHeader {
timeval tuple_stime; // 34..37
} __ attribute __((__ packed__));
void set_value(timeval& stime){
}
int main(){
TupleHeader tuple;
set_value(tuple.tuple_stime);
return 0;
}
我在 g ++ - 3.4.2 和 g ++ - 4.8.3 :
attribute-1.cc:在函数`int main()':
attribute-1.cc:13:error:不能绑定压缩字段`tuple.TupleHeader :: tuple_stime'到`timeval&'
在我定义 timeval code>:
$$> struct timeval2
{
__time_t tv_sec;
__suseconds_t tv_usec;
} __ attribute __((__ packed__));
错误消失了,但我不想定义一个已经存在于< bits / time.h> 。什么是其他方法来纠正这个错误?非常感谢!
解决方案这取决于你想要什么。如果你想要内部的timeval也是紧包装,重复的struct声明是你唯一的选择:默认打包的结构和紧包结构有成员具有相同的名称,但包装的区别使他们根本不同的类型。 (FWIW,因为你显然试图节省空间,你可以利用这个机会使它成为一个位域,并且 tv_usec 只有二十位!)
另一方面,如果你不关心在时间间隔内填充 - 只在它和其他结构之间 - 你的另一个选项是声明它为 char tuple_stime [sizeof(timeval)] ,并根据需要强制转换。 (不要忘记别名混淆问题。)
when I compiled the following code:
#include <sys/time.h> #include <stdio.h> struct TupleHeader { timeval tuple_stime; // 34..37 }__attribute__((__packed__)); void set_value(timeval& stime){ } int main(){ TupleHeader tuple; set_value(tuple.tuple_stime); return 0; }I got the error under g++-3.4.2 and g++-4.8.3:
attribute-1.cc: In function `int main()': attribute-1.cc:13: error: cannot bind packed field `tuple.TupleHeader::tuple_stime' to `timeval&'After I defined timeval myself as follows and changed all timevals in the above code into timeval2:
struct timeval2 { __time_t tv_sec; __suseconds_t tv_usec; }__attribute__((__packed__));the error is gone, but I don't want to define a struct that already exists in <bits/time.h> . What are other methods to correct this error? Thanks a lot!
解决方案It depends on what you want. If you want the inner timeval to be tight-packed as well, repeating the struct declaration is pretty much your only option: The default-packed struct and the tight-packed structs have members with the same names, but the difference in packing makes them fundamentally different types. (FWIW, since you're clearly trying to save space anyway, you can take this opportunity to make it a bitfield, and allot tv_usec only twenty bits!)
If, on the other hand, you don't care about there being padding within the timeval -- only between it and the other structs -- your other option is to declare it as char tuple_stime[sizeof(timeval)] instead, and cast it as necessary. (Don't forget about aliasing concerns.)
这篇关于有关__attribute __((__ packed__))的c ++编译错误的其他方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!