C++联合阵列在32/64位不同
我的代码:
union FIELD {
int n;
char c;
const char *s;
FIELD(){}
FIELD(int v){ n = v; }
FIELD(char v){ c = v; }
FIELD(const char* v){ s = v; }
};
struct SF {
const char* s0;
char s1;
int s2;
const char* s3;
};
int main() {
printf("sizeof(long) = %ld\n", sizeof(long));
printf("now is %d bit\n", sizeof(long) == 8?64:32);
FIELD arrField[] = {
FIELD("any 8 words 0 mixed"), FIELD('d'), FIELD(251356), FIELD("edcba")
};
SF* sf0 = (SF*)&arrField;
printf("sf0->s0 = %s, ", sf0->s0);
printf("sf0->s1 = %c, ", sf0->s1);
printf("sf0->s2 = %d, ", sf0->s2);
printf("sf0->s3 = %s\n", sf0->s3);
}
当我使用默认的64位执行输出时:
set_target_properties(untitled PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
我的问题是,如何使64位程序具有与32位程序相同的输出行为?
My code:
union FIELD {
int n;
char c;
const char *s;
FIELD(){}
FIELD(int v){ n = v; }
FIELD(char v){ c = v; }
FIELD(const char* v){ s = v; }
};
struct SF {
const char* s0;
char s1;
int s2;
const char* s3;
};
int main() {
printf("sizeof(long) = %ld\n", sizeof(long));
printf("now is %d bit\n", sizeof(long) == 8?64:32);
FIELD arrField[] = {
FIELD("any 8 words 0 mixed"), FIELD('d'), FIELD(251356), FIELD("edcba")
};
SF* sf0 = (SF*)&arrField;
printf("sf0->s0 = %s, ", sf0->s0);
printf("sf0->s1 = %c, ", sf0->s1);
printf("sf0->s2 = %d, ", sf0->s2);
printf("sf0->s3 = %s\n", sf0->s3);
}
When I use the default 64-bit execution output:
I add the compilation parameters in CMakeLists.txt
:
set_target_properties(untitled PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-m32")
It will compile the 32-bit program, then run and output:
My question is, how can I make a 64-bit program have the same output behavior as a 32-bit program?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
alignas(field)
应用于sf
的每个成员变量。此外,您不能依靠
长
的大小来告诉64位和32位系统。检查指针的大小来执行此操作。在大约64位系统上长
是32位。例如,我的系统就是这种情况。此外,
%ld
需要一个长
参数,但是sizeof
运算符产量size> size> size_t
,除了不是在未经必要的情况下,匹配长
大小。您需要在此处添加一个安全性(或者只使用std :: cout
,它会根据<<<
自动选择正确的转换。操作员)。Apply
alignas(FIELD)
to every single member variable ofSF
.Additionally you cannot rely on the size of
long
to tell 64 bit and 32 bit systems appart. Check the size of a pointer to do this. On some 64 bit systemslong
is 32 bit. This is the case for my system for example.Furthermore
%ld
requires along
parameter, but thesizeof
operator yieldssize_t
which is unsigned in addition to not necesarily matchinglong
in size. You need to add a cast there to be safe (or just go withstd::cout
which automatically chooses the correct conversion based on the second operand of the<<
operator).