C 为特定用例对齐字符串文字

Scr*_*Cat 6 c string gcc alignment clang

我试图以特定的方式对齐字符串文字,因为我在代码中使用它的方式相当具体。我不想将它分配给变量,例如我的许多函数都将它用作直接参数。我希望它能够在本地范围或全局范围内工作。

使用示例:

char *str = ALIGNED_STRING("blah"); //what I want
foo(ALIGNED_STRING("blah")); //what I want

_Alignas(16) char str[] = "blah"; //not what I want (but would correctly align the string)
Run Code Online (Sandbox Code Playgroud)

理想的解决方案是(_Alignas(16) char[]){ "blah" }使用 GCC/Clang 编译器扩展进行对齐或更糟糕的情况(__attribute__((alignment(16))) char[]){ "blah" },但这两种方法都不起作用(它们被忽略并使用类型的默认对齐方式)。

所以我的下一个想法是自己对齐它,然后使用该字符串的函数可以正确修复它。例如#define ALIGNED_STRING(str) (char*)(((uintptr_t)(char[]){ "xxxxxxxxxxxxxxx" str } + 16 - 1) & ~(16 - 1))(其中包含“x”的字符串表示了解在哪里可以找到真正的字符串所需的数据,这很简单,但仅作为示例假设“x”很好)。现在,它在本地范围内工作正常,但在全局范围内失败。由于编译器抱怨它不是编译时常量(错误:初始化器元素不是编译时常量);我本以为它会起作用,但似乎只有加法和减法是编译时指针上的有效操作。

所以我想知道是否有办法实现我想做的事情?目前我只是使用后一个示例(填充和手动对齐)并避免在全局范围内使用它(但我真的很想这样做)。最好的解决方案将避免需要进行运行时调整(就像使用对齐限定符一样),但这似乎不可能,除非我将其应用于变量(但如上所述,这不是我想要做的)。

chu*_*ica 4

能够通过复合文字来接近OP的需求。(C99)

#include <stdio.h>
#include <stddef.h>

void bar(const char *s) {
  printf("%p %s\n", (void*)s, s);
}

//                         v-- compound literal --------------------------v
#define ALIGNED_STRING(S)  (struct { _Alignas(16) char s[sizeof S]; }){ S }.s

int main() {
  char s[] = "12";
  bar(s);
  char t[] = "34";
  bar(t);
  bar(ALIGNED_STRING("asdfas"));
  char *u = ALIGNED_STRING("agsdas");
  bar(u);
}
Run Code Online (Sandbox Code Playgroud)

输出

0x28cc2d 12
0x28cc2a 34
0x28cc30 asdfas  // 16 Aligned
0x28cc20 agsdas  // 16 Aligned
Run Code Online (Sandbox Code Playgroud)