- 测试1:通过对比源码、预处理后代码、汇编后代码,发现,汇编后,宏与内联的实现效率完全一样。
gcc -O1 inline_macro_diff.c -E
gcc -O1 inline_macro_diff.c -S
gcc -O1 inline_macro_diff.c -c
gcc -O1 inline_macro_diff.c
objdump -d inline_macro_diff.o
源代码:
1 #include <stdio.h>
2 #define add(x, y) ( (x) + (y))
3
4 inline int add_fun(int x, int y)
5 {
6 return x+y;
7 }
8
9
10 void test()
11 {
12 int a = 100;
13 int b = 11;
14 int result1 = add(a, b);
15 int result2 = add_fun(a, b);
16 printf("the result1 is %d, result2 is %d\n", result1, result2);
17 }
18
19 int main()
20 {
21 test();
22 return 0;
23 }
预处理后:
# 2 "inline_macro_diff.c" 2
inline int add_fun(int x, int y)
{
return x+y;
}
void test()
{
int a = 100;
int b = 11;
int result1 = ( (a) + (b));
int result2 = add_fun(a, b);
printf("the result1 is %d, result2 is %d\n", result1, result2);
}
int main()
{
test();
return 0;
}
汇编后:
34 .globl test
35 .type test, @function
36 test:
37 .LFB14:
38 .loc 1 11 0
39 pushl %ebp
40 .LCFI2:
41 movl %esp, %ebp
42 .LCFI3:
43 subl $24, %esp
44 .LCFI4:
45 .loc 1 16 0
46 movl $111, 8(%esp)
47 movl $111, 4(%esp) // 内联与宏的实现,完全一样。
48 movl $.LC0, (%esp)
49 call printf
50 .loc 1 17 0
51 leave
52 ret
- 测试2:##与#的作用
#define fun(type,para) fun_##type(para)
void fun_char(char ch)
{
ch = 'a';
}
void fun_int(int para1)
{
para1 += 10;
}
void test()
{
char ch = 'a';
int idata = 99;
fun(char,ch);
fun(int,idata);
}
int main()
{
test();
return 0;
}