【发布时间】:2010-11-30 21:50:24
【问题描述】:
这几天让我发疯了。如果我将数组声明为static,则无法让数组与 16 对齐。
非常感谢任何帮助。
修订版:
#include <stdio.h>
#include <assert.h>
#define MAX_INPUTS 250
int main()
{
float input[MAX_INPUTS] __attribute__ ((__aligned__(16)));
printf("Address of input: %p\n", input);
printf("Assert1: %x\n", ( ((int) (input)) ) );
printf("Assert2: %x\n", ( ((int) (input)) % 16 ) );
printf("Assert3: %x\n", ( ((int) (input)) % 16 ) == 0 );
assert ( ( ((int) (input)) ) );
assert ( ( ((int) (input)) % 16 ) ); /* Fails */
assert ( ( ((int) (input)) % 16 ) == 0 ); /* Passes */
return 0;
}
输出是:
Address of input: 0022FB70
Assert1: 22fb70
Assert2: 0
Assert3: 1
Assertion failed: ( ((int) (input)) % 16 ), file aligntest.c, line 16
正如预期的那样,Assert 2 失败,因为地址以 0 结尾。但是,使用:
static float input[MAX_INPUTS] __attribute__ ((__aligned__(16)));
输出是:
Address of input: 00404028
Assert1: 404028
Assert2: 8
Assert3: 1
Assertion failed: ( ((int) (input)) % 16 ), file aligntest.c, line 16
断言 2 仍然失败,尽管结果非零。当 Assert2 被注释掉时,Assert3 通过(有或没有静态声明)并且程序正常终止。
我在 Intel Core 2 Duo 上使用 MinGw gcc 4.4.0,运行 XP Pro。
【问题讨论】:
-
@Ian,查看对@pmg 答案的补充——我想你会发现那里描述的问题已经足够好(以及解决方案,即引入 volatiles 以阻止 gcc 疯狂寻求优化)。
-
@Ian,重新更新:assert2 将 always 失败,原因与 assert3 将 always 通过的原因相同(地址是否实际上由链接器与否)。 GCC 认为它将被对齐并丢弃 assert1/3 并可能将 assert2 优化为 assert(0)。
-
检查我的(第二个)答案的最新更新
-
@pmg - 我可以看到你在用强制对齐做什么,它有效,所以谢谢你。我将不得不与我的同事(他没有遇到这个问题)讨论这是否是该项目的跑步者。在我们弄清楚为什么我的系统在他工作的地方失败之前,它可能至少必须是一个临时修复。再次感谢