关于C语言中 函数重复定义的问题


下面的三个文件中,前两文件中的函数定义冲突了,其中add函数的实现互不相同。
①当把两个source分别编译成source.o和source2.o之后,再跟test.c编译的test.o进行链接(即链接三个.o文件)时,gcc会提示重复定义的错误。
②当把两个source分别编译成libsource.so和libsource2.so之后,再跟test.c编译成的test.o进行链接(即链接一个.o和两个.so文件)时,gcc则不会提示重复定义,而且所调用的add函数跟链接时两个.so文件的先后顺序有关,哪个在前面就调哪个中的add函数。

问题:test.o链接两个.o时,跟链接两个.so时区别在哪儿(在重复定义方面)?为什么第一种情况链接时会重复定义,而第二种情况不会?
source.c

   
  1 #include <stdlib.h>
  
2 #include <stdio.h>
3
4
5 int add(int a, int b)
6 {
**7 puts("There's no add function now!");
8 return 0;**
9 }
10
11 int getSum(int a, int b)
12 {
13 return add(a, b);
14 }
15

source2.c

   
  1 #include <stdlib.h>
  
2 #include <stdio.h>
3
4 int add(int a, int b)
5 {
6 return a+b;
7 }
8
9 int getSum(int a, int b)
10 {
11 return add(a, b);
12 }

test.c

   
  1 #include <stdlib.h>
  
2 #include <stdio.h>
3
4 extern int getSum(int a, int b);
5 /*
6 int getSum(int a, int b)
7 {
8 return a+b;
9 }
10 */
11
12 int main()
13 {
14 int a = 3;
15 int b = 4;
16 printf("3+4=%d\n", getSum(a, b));
17 return 0;
18 }

c 编译器

断てるもDなし 10 years, 5 months ago

Your Answer