在#Include指令中使用C文件时C程序出错(多重定义错误)

Jee*_*eet 2 c linker-errors

场景:

在Netbeans IDE中创建的AC应用程序,包含以下两个文件:

some_function.c

#include <stdio.h>
int function_1(int a, int b){
    printf("Entered Value is = %d & %d\n",a,b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

newmain.c

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
    //function_2(); //Error //function name not allowed
    function_1();
    function_1(1);
    function_1(1,2);
    return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)

当在C程序中学习头文件的需要时,我尝试了上述应用程序(原样).它被编译并给出如下输出

输入值= 4200800&102
输入值= 1和102
输入值= 1和2

问题1 :(我意识到,在开始阶段,理解链接器程序的过程很难,因此我问这个问题.)我的假设是正确的,当链接时,"链接器将检查函数名称而不是参数"在没有使用头文件的情况下?

关于头文件的使用,我遇到了这个链接,它说,我们可以使用#include包含C文件本身.所以,我在newmain.c文件中使用了以下行

#include "some_function.c"
Run Code Online (Sandbox Code Playgroud)

正如所料,它显示了以下错误

错误:函数'function_1()'
错误的参数太少:函数'function_1(1)'的参数太少

而且,我得到了以下(意外)错误:

some_function.c:8:`function_1'some_function.c:8的多重定义
:首先在这里定义

问题2:包含'c'文件本身时我做了什么错误,因为它给出了上述(意外)错误?

jua*_*nza 5

您可能正在使用C的C99前方言,它具有"隐式函数声明".这意味着没有声明的函数被用来拥有这种签名:

int function_1();
Run Code Online (Sandbox Code Playgroud)

即返回int并接受任何类型的任意数量的参数.传递与函数定义不兼容的参数列表时,将在运行时调用未定义的行为.

关于多重定义错误,请考虑它.您包含的每个翻译单元some_function.c都有自己的功能定义.就好像你已经在每个其他.c文件中编写了该定义.C不允许在程序/库中进行多个定义.