Hi,
I work in project in which I have the following code:
file1.c
extern const int z;
int x;
do_some_stuff_to_calculate_x();
y = x / z;
do_some_stuff_with_y();
file2.c
const int z = Z_INIT_VALUE; // some value defined in some .h file.
The point of interest is the division in file1.c
. Since z
is extern
, so it is not known in compile time [it will be defined in linking time].
So, the compiler can't optimize the division.
I know that if value of z
is known at compile time the compiler will convert the division to multiplication and some other manipulations.
Note that file1.c will be delivered as a library, so re-compiling file1.c
with file2.c
is not an option.
Do any one know away to make the linker optimize such things? Or any other trick to avoid this EXPENSIVE division?
Thx :)
Update:
Well, after I saw some answers I noticed that some more details are required to make this question more informative.
- I use a microcontroller from company called renesas (Family SH725).
- This division is found in MANY places in the code, with many variants.
- Most of the other stuff in the code is directly reading and writing to registers and ports (no overhead, i.e: *0x0ABCDEFF = 15).
The functions which include division are normally looks like this.
extern const int common_divisor;
extern const int common_addition;
void handleTheDamnInterrupt(void)
{
int x = *(REG_FOO_1);
int y = x / common_divisor;
y += common_addition;
if( x > some_value )
{
y += blah_blah;
}
else
{
y += foo_bar;
}
*(REG_BAR_1) = y;
}
This function is the typical function form in all the program. Can't know exactly how much division is affecting the program because I have many of these functions with different periodicity.
But when I tried to remove the extern
from the const
and gave it arbitrary value, it was better.