日期:2014-05-16  浏览次数:20659 次

关于C语言内联函数
今天对内联函数做了一个简单的测试,但是编译器貌似并没有对内联函数进行展开。测试如下:
inline.c

inline int test(int i)
{
  return i+1;
}

int main()
{
  int j=1;
  j=test(j);
  return 0;
}

gcc -S inline.c -o inline.s

查看inline.s部分内容如下:

main:
.LFB1:
        .cfi_startproc
        pushl   %ebp
        .cfi_def_cfa_offset 8
        .cfi_offset 5, -8
        movl    %esp, %ebp
        .cfi_def_cfa_register 5
        subl    $20, %esp
        movl    $1, -4(%ebp)
        movl    -4(%ebp), %eax
        movl    %eax, (%esp)
        call    test
        movl    %eax, -4(%ebp)
        movl    $0, %eax
        leave
        .cfi_restore 5
        .cfi_def_cfa 4, 4
        ret

可以看到,汇编代码中call test 表示test函数是作为普通函数被调用,而非内联函数展开。 求达人解答 谢谢

------解决方案--------------------
内联不内联由编译器决定.

------解决方案--------------------
inline是为了优化而生的, 用gcc -O才能看到效果。

inline int test(int i)
{
  return i+1;
}

int main(int argc, char *argv[])
{
  int j=argc;
  j=test(j);
  printf("%d\n", j);
  return 0;
}


.file "inline.c"
.text
.globl _test
.def _test; .scl 2; .type 32; .endef
_test:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %eax
incl %eax
popl %ebp
ret
.def ___main; .scl 2; .type 32; .endef
.section .rdata,"dr"
LC0:
.ascii "%d\12\0"
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
pushl %ebp
movl %esp, %ebp
subl $8, %esp
andl $-16, %esp
movl $16, %eax
call __alloca
call ___main
movl 8(%ebp), %eax
incl %eax
movl %eax, 4(%esp)
movl $LC0, (%esp)
call _printf
movl $0, %eax
leave
ret
.def _printf; .scl 2; .type 32; .endef