用C定义两次函数 [英] defining a function twice in C
问题描述
我有一个问题。我写这篇code,A.H.交流转换器和main.c中:
i have a problem. i wrote this code, a.h. a.c and the main.c:
文件:A.H
#ifndef _a_H
#define _a_H
int poly (int a, int b, int c, int x);
int square (int x)
{
return x*x;
}
#endif // _a_H
文件:交流转换器
file: a.c
#include "a.h"
int poly (int a, int b, int c, int x)
{
return a*square(x) + b * x +c;
}
文件:main.c中
file: main.c
#include <stdio.h>
#include "a.h"
int main()
{
int p1 = poly1 (1 ,2 , 1, 5);
int p2 = poly2 (1 ,1 , 3, 5);
printf ("p1 = %d, p2 = %d\n", p1, p2);
return 0;
}
和我得到了一个错误:
/tmp/ccKKrQ7u.o:在函数'方':结果
main.c中:(文字+为0x0):的'方'结果多重定义
/tmp/ccwJoxlY.o:a.c:(.text+0x0):先在这里定义搜索
collect2:劳工处返回1退出状态
/tmp/ccKKrQ7u.o: In function 'square':
main.c:(.text+0x0): multiple definition of 'square'
/tmp/ccwJoxlY.o:a.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status
让我感动的功能方的交流转换器文件的执行和它的作品。
so i moved the implementation of the function square to the a.c file and it works.
没有任何一个知道为什么吗?
does any one know why?
感谢名单
推荐答案
一般来说,* .c文件编译成* .o文件和* .o文件链接到生成可执行。 * .h文件不会被编译,它们在* .c文件包含文本形式,在该点它们包含(#include)。
Generally speaking, *.c files are compiled into *.o files, and *.o files are linked to build the executable. *.h files aren't compiled, they are included textually in the *.c files, at the point they are #included.
因此,通过#包括A.H两次,在两个不同的* .c文件,您放置定义方()为两个单独的文件。当这些被编译,你结束了()平方的两个副本,一个在每个* .o文件将。然后,当你将它们链接,链接器看到两个文件,并生成一个错误。
So by #including "a.h" twice, in two separate *.c files, you've placed your definition for square() into two separate files. When these are compiled, you end up with two copies of square(), one in each *.o file. Then when you link them, the linker sees the two files, and generates an error.
如何避免这种情况?你已经发现了这一点。不要把函数定义在* .h文件。把他们在* .c文件,只有把函数声明中的* .h文件。
How to avoid this? You've already discovered this. Don't put function definitions in *.h files. Put them in *.c files, and only put the function declarations in the *.h files.
这篇关于用C定义两次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!