如何将字符串文字与4的倍数对齐? [英] How can I align a string literal to an address which is multiple of 4?

查看:110
本文介绍了如何将字符串文字与4的倍数对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保给定的字符串文字以2的倍数或更好的4的地址结尾。

I'd like to ensure that a given string literal ends up at an address that is a multiple of 2, or even better, 4.

是否有任何的方法,最好不使用任何编译器特定的扩展?

Is there any way to achieve that, preferably without using any compiler-specific extensions? Or is it impossible?

我想这样做,因此字符串地址的最低位是0,可以用作标签位。

I'd like to do this so the lowermost bits of the string address are 0 and can be (ab)used as tag bits.

推荐答案

在C99中,您可以使用联合来完成此操作,例如

In C99 you can do this using a union, for example

#define ALIGNED_STR_UNION(N, S) const union { char s[sizeof S]; int align; } N = { S }
ALIGNED_STR_UNION(sssu, "XYZABC");

根据需要调整类型 int

因此, sssu.s 是指字符。

.s 可以避免,例如

#define ALIGNED_STR(S) ((const union { char s[sizeof S]; int align; }){ S }.s)
const char *sss = ALIGNED_STR("XYZABC");

但是,此版本浪费了指针的空间(包括位置无关代码的相对重定位),并且不允许在函数中声明静态文字。

However, this version wastes space on the pointer (including a relative relocation for position independent code) and does not allow declaring static literals in functions.

最好使用非标准对齐属性代替。

It is probably better to use the non-standard alignment attributes instead of this.

这篇关于如何将字符串文字与4的倍数对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆