문제

Let's say we have this code:

inline int func_2 (int a, int b) {
  return time() + a * b;
}

int main (void) {
  int x = (int (*[])(int, int)){func_1, func_2, func_3}[1](6, 7);
}

Can gcc be somehow tricked to really inline the indirect calls to func_*?

After compiling the code with -O2 and -O3, I could still spot a call func_2 instruction in the assembly output.

I know this hairy expression can be converted into a bulky switch statement with inlined calls for each case, but I prefer the former for its compactness.

도움이 되었습니까?

해결책

if it does not hurt you to allocate some space in the data segment, you can try like this:

static int func_2 (int a, int b) {
    return time() + a * b;
}

static int (* const ftab[])(int,int) = {func_1, func_2, func_3};

int foo (void) {
    return ftab[1](6,7);
}

my gcc 4.4.5 correctly inlines the function with -O2.

The aggregate initializer inside the code of the function does not forward the constant as we expect, I don't know wheter it's a gcc bug or our misunderstanding of some C rule.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top