Consider the macro below. How can I unroll the for loops using macros and export lots of macros cleanly into a readable header?
macro.h
#define ARR(n) \
typedef int arr##n[n]; \
void arr##n##_add(arr##n res, arr##n x, arr##n y){ \
int i = 0; \
for (; i < n; i++) { \
res[i] = x[i] + y[i]; \
} \
}
ARR(3)
ARR(4)
Running this through the pre-processor with gcc -E -P macro.h > out.h
we get:
out.h
typedef int arr3[3];
void arr3_add(arr3 res, arr3 x, arr3 y){
int i = 0;
for (; i < 3; i++) {
res[i] = x[i] + y[i];
}
}
typedef int arr4[4];
void arr4_add(arr4 res, arr4 x, arr4 y){
int i = 0;
for (; i < 4; i++) {
res[i] = x[i] + y[i];
}
}
Using token pasting like above we avoid having to repeat definitions. Now there are two things I would like to know:
How can each
for(;i; i < n)
be replaced (unrolled) with e.g:res[0] = x[0] + y[0]; res[1] = x[1] + y[1]; ... res[n] = x[n] + y[n];
What is a clean way of exporting lots of macro hackery into a readable header? Should I create a shell function inside my
make
file exports the final header to aninclude
directory?
Maybe there are better ways of doing this. Any alternatives welcome.