astomo.us

static functions in c

November 7th, 2009

Today I was reading the slides from Felix von Leitner’s talk on C compiler optimizations (given at the recent Linux Kongress). Basically his point is that there is no point in making your code confusing in an attempt to optimize it b/c usually the resulting object code will not be faster. I’m not sure how true that is in general (it doesn’t seem to be the case with OpenCL at least in my experience), but I really like his point. The slides are also a good read if you like learning semi-obscure C tricks. For example if you want to inline a function in C its best to actually not use the inline keyword. This ‘destroys code locality’ according to Felix which Im assuming means that it can cause pointers to what is apparently the same function to compare not equal to one another. However what you can do is declare them static if you’re calling them exactly once. In that case the compiler will inline the function. For example, when compiled with the command gcc -S -O2, the code:

static long abs2(long x) {
return x>=0?x:-x;
} /* Note: > vs >= */

long abs3(long x) {
return x>=0 ? x : -x;
}

int main(int argc, char *argv[]) {
int x = 11;
int y;

y = abs2(x);
y = abs3(x);

return 0;

}

will produce assembly that contains no definition of abs2. However if you add a second call to abs2 and look at the assembly again you’ll find that all of a sudden you have an extra:


_abs2:
LFB2:
  pushq  %rbp
LCFI0:
  movq  %rsp, %rbp
LCFI1:
  movq  %rdi, %rdx
  sarq  $63, %rdx
  movq  %rdx, %rax
  xorq  %rdi, %rax
  subq  %rdx, %rax
  leave
  ret
LFE2:
  .align 4,0x90

Leave a Reply