Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force compile-time calculations C

Let's say that I have a file, in which I do some calculations on some data. It could be (very psedo calculations) like this:

void hash_value(unsigned char* value){
    unsigned char i;
    for(i + 0; i < 10; i++){
        value[i] ^= (0x1b+i)
    }
}

void break_value(unsigned char* value){
    unsigned char i;
    for(i = 0; i < 10; i++)
        value[i] &= 0x82;
}

void affect_value(unsigned char* value){
    hash_value(value);
    break_value(value);
}

In my main I would the do the following:

#include "smart_calculations.h"

int main() {
    unsigned char value[16] = {'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S'};
    affect_value(value);
    // Do other stuff

}

Since I do not intend to change the contents of the value array, but I need to do the calculations before I can continue doing other stuff. I guess that some compilers will recognize the, and optimize the code, such that the data is computed at compiletime.

My question is, how do I (as best possible) force the compiler to do this optimization at compiletime, such that methods in the "Smart_calculations" file isn't wasting space in the final product, and the initial values of the array isn't compiled in to the program?

like image 304
Benjamin Larsen Avatar asked Sep 22 '18 08:09

Benjamin Larsen


1 Answers

The easiest, most general method is to do your staging manually. That is, run the code that does the pre-calculations explicitly during your build phase and only compile the results into your program.

If you want to do it all in C, you'd create a smart_calculations.c with a main function. You'd first compile a smart_calculations executable that produces

unsigned char value[16] = { ... };

as output. Place this output in a file, e.g. smart_generated.h.

Your real program would then either #include this file:

int main() {
    #include "smart_generated.h"  // 'value' is now a local variable
    // Do other stuff    
}

... or (if you want a global variable instead) you'd put the generated results in a .c file and link it into your program.

Of course with this approach you're not limited to doing the "smart calculations" in C. You can use any programming language or environment that's available at build time.

like image 188
melpomene Avatar answered Sep 17 '22 13:09

melpomene