Issue
Consider this piece of code, where two global variables are defined:
int a;
int b;
As far as I know, the compiler may or may not place a
and b
in adjacent memory locations (please let me know if this is incorrect). For example, with GCC one may compile with -fdata-sections
and reorder the two sections or whatever.
Is it possible to specify that a
and b
must be adjacent (in the sense that &a + 1 == &b
), in either standard or GNU extended C?
Background: I am making an OpenGL loader, which is literally (omitting casts):
void (*glActiveShaderProgram)(GLuint, GLuint);
void (*glActiveTexture)(GLenum);
...
void load_gl(void (*(*loader)(char *))()) {
glActiveShaderProgram = load("glActiveShaderProgram");
glActiveTexture = load("glActiveTexture");
...
}
Simple enough, but every call to load
compiles into a call to load
. Since there is a relatively large number of functions to load, that can take up a lot of code space. (That is the reason I dropped glad.)
So I had something like this, which reduces binary size by ~30kB, which is extremely important for me:
char names[] = "glActiveShaderProgram glActiveTexture ...";
char *p = names, *pp;
for (int i = 0; i < COUNT; ++i) {
pp = strchr(names, ' ');
*pp = '\0';
(&glActiveShaderProgram)[i] = load(p);
p = pp + 1;
}
But this does assume the specific layout of these function pointers. Currently I wrap the function pointers in a struct which is type-punned into an array of pointers, like this:
union { struct {
void (*glActiveShaderProgram)(GLuint, GLuint);
void (*glActiveTexture)(GLenum);
...
}; void (*table[COUNT])(); } gl;
But then one #define
for every function is required to make the user happy. So I wonder if there exists some more elegant way to specify the layout of global variables.
Solution
As Ted suggested in the comment. You could put the variables next to each other inside an array?
int ab[2] = {a, b};
Another way to ensure adjacent memory placement is with a packed struct. example
Answered By - Gaai Answer Checked By - Willingham (WPSolving Volunteer)