小编jga*_*lar的帖子

宏如何将对齐的指针返回未对齐的值?

我一直在研究现有的C99代码库,该代码库在各处使用指向打包结构成员的指针。这会导致出现形式警告。

my_file.c:xxx:yy: error: taking address of packed member of 'struct some_packed_struct' may result in an unaligned pointer value [-Werror=address-of-packed-member]
Run Code Online (Sandbox Code Playgroud)

大多数时候,这些警告是在将指针传递给函数的结构成员时生成的。例如:

my_file.c:xxx:yy: error: taking address of packed member of 'struct some_packed_struct' may result in an unaligned pointer value [-Werror=address-of-packed-member]
Run Code Online (Sandbox Code Playgroud)

有很多解决此问题的方法。立即想到的是memcpy()将相同类型的堆栈分配变量的值传递给该堆栈变量。


int bar(const int *val)
{ ... }

struct {
    int a;
    char b;
    int c;
} __attribute__((packed)) foo;

// &foo.c is not aligned
bar(&foo.c)
Run Code Online (Sandbox Code Playgroud)

在此过程中,它将产生许多样板代码,我希望避免引入。

目前,我一直在考虑使用以下形式的宏

#define ALIGN_VALUE_PTR(val) (&((const typeof(val)) { val }))

bar(ALIGN_VALUE_PTR(foo.c));
Run Code Online (Sandbox Code Playgroud)

这适用于标量类型。但是,可以预见的是,如果val为a struct,则将不起作用。 …

c c99 c-preprocessor

3
推荐指数
1
解决办法
87
查看次数

标签 统计

c ×1

c-preprocessor ×1

c99 ×1