C++ 对齐数组的未对齐属性

标签 c++ arrays alignment memory-alignment

编辑:这是我的一个工作项目。在职的。 我在 .cpp 文件的开头声明了一些字符数组(甚至在 #include 部分之前)。然后我可以将这些数组与“16 字节对齐变量的说明”一起使用。

问题:如果我在另一个 .cpp 文件中使用这个 .cpp 文件作为包含会发生什么?我也可以在其他项目中使用该数组进行对齐操作吗?

问题2:这有捷径吗?我不想将所有变量都放在开头。

一些代码:(我处理了一些 16 字节对齐的数组)

    //I put these arrays at the beginning, so they are aligned
//for the movaps instructions(x2 speed for reading and writing memory)
float v1[16];
float v2[16];
char counters[32];
char array_of_ones[32];
char source_array[4096];
char destination_array[4096];   
struct bit_field
{
    bf1:32; 
    bf2:32;
    bf3:32;
    bf4:32;
}some_area;
struct bit_mask_x
{
    bf1:32;
    bf2:32;
    bf3:32;
    bf4:32;
}some_mask;
float var_fast[16];
char alignment_purge[5];    //for the unalignment tests
char unaligned_source_array[4096];
char unaligned_destination_array[4096];



#include <math.h>
#include<stdlib.h>
#include<stdio.h>
#include<time.h>
.....
.....

如果我像这样将这个程序包含在另一个程序中会发生什么:

#include <math.h>
#include<my_aligned.h> <-------- or my_aligned.cpp
#include<stdio.h>
#include<time.h>

我必须为此使用 .h 文件吗?

谢谢...

最佳答案

如果这能正确对齐您的变量,您是否真的尝试过?当您编译时,可执行文件总是有一个 header ,其大小可能不是 16 的倍数。此外,alignment_purge 可能不会真正使它后面的变量不对齐,因为编译器可能会添加填充。最后,标题不引入变量,因此如果您将变量放在标题上方或下方,这不会改变任何内容。

可以看看this question查看如何请求对齐内存。

附带说明一下,通常您不希望将源文件包含到另一个文件中。参见 this question关于这个问题。

关于C++ 对齐数组的未对齐属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11645596/

相关文章:

C++ NULL 指针和 const 正确性

c++ - vector 到函数内的数组

c++ - 这个 static_assert 会被触发吗?

java - 我怎样才能用 42,000 个键优化这个 HashMap

html - 在 Sharepoint 2013 中将嵌入的 SWF 对齐到中心

html - Flexbox - 将元素左对齐并居中

c++ - { token 之前的预期类名

python - 合并数组并根据python中的键添加

java - 元素在数组中的位置

在页脚中对齐文本和图像的 Css 问题