Search code examples
c++arraysalignmentmemory-alignment

C++ aligned unaligned property of arrays


EDIT:This is from a working project of mine. Working. I declared some char arrays at the beginning of .cpp file(even before the #include parts). Then i could use these arrays with "instructions for 16-Byte aligned variables".

Question: what happens if i use this .cpp file in another .cpp file as an include? Could i use that arrays for aligned operations in another projects too?

Question-2: is there a short-cut for this? I dont want to place all my variables in the beginning.

Some of the code:(i worked on some 16-Byte-aligned arrays)

    //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>
.....
.....

What happens if i include this program in another like this:

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

Do i have to use a .h file for this?

Thanks...


Solution

  • Have you actually tried if this aligns your variables correctly? When you compile, the executable always has a header whose size may not be a multiple of 16. Also, alignment_purge may not really get the variables following it out of alignment, because the compiler may add padding. Finally, the headers don't introduce variables, so if you put your variables above or below headers, that doesn't change anything.

    You can take a look at this question to see how to request aligned memory.

    As a side note, normally you wouldn't want to include source files into another file. See this question on this subject.