[英]Error in C program when using a C file in #Include directive (Multiple definition error)
场景:
在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;
}
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);
}
当了解C程序中头文件的需要时,我尝试了上面的应用程序(原样)。 它被编译并给出如下输出
输入的值是= 4200800和102
输入的值是= 1和102
输入值为= 1&2
问题1 :(在开始阶段,我意识到要了解链接器程序的过程很困难,因此我会问这个问题。)我的假设正确吗,即链接时,“链接器将检查函数名,而不是函数名。在没有使用头文件的情况下使用“参数”?
关于头文件的用法,我遇到了此链接 ,它的意思是,我们可以使用#include包含C文件本身。 因此,我在文件newmain.c中使用了以下行
#include "some_function.c"
如预期的那样显示以下错误
错误:函数'function_1()'的参数太少
错误:函数'function_1(1)'的参数太少
而且,我遇到了以下(意外)错误:
some_function.c:8:“ function_1”的多个定义
some_function.c:8:首先在这里定义
问题2:当包含“ c”文件本身时,我做了什么错误,因为它给出了上述(意外)错误?
您可能正在使用C99之前的方言C,该方言具有“隐式函数声明”。 这意味着将不带声明的函数视为具有这种签名:
int function_1();
即返回一个int
并接受任意数量的任何类型的参数。 当传递与函数定义不兼容的参数列表时,将在运行时调用未定义的行为 。
关于多重定义错误,请考虑一下。 您包括some_function.c
每个翻译单元将具有自己的函数定义。 就像您已经在每个其他.c
文件中写入了该定义一样。 C不允许程序/库中有多个定义。
我(发问者)将此答案发布给了一些C编程入门者以快速了解。 此答案来自@juanchopanza和@Sam Protsenko的答案 ,它们在这篇文章中。
问题1: C中的隐式函数声明
问题2:使用以下行时
#include "some_function.c"
在预处理程序活动之后,结果应用程序将发生如下变化
some_function.c
#include <stdio.h>
int function_1(int a, int b){
printf("Entered Value is = %d & %d\n",a,b);
return 0;
}
newmain.c
#include <stdio.h>
#include <stdlib.h>
/*"#include "some_function.c"" replace begin by preprocessor*/
#include <stdio.h>
int function_1(int a, int b){
printf("Entered Value is = %d & %d\n",a,b);
return 0;
}
/*"#include "some_function.c"" replace end by preprocessor*/
int main(int argc, char** argv) {
//function_2(); //Error //function name not allowed
//function_1(); //Error
//function_1(1); //Error
function_1(1,2);
return (EXIT_SUCCESS);
}
注意:在上面的两个文件中,函数function_1位于两个位置
所以现在下面的错误是有意义的
some_function.c:8:“ function_1”的多个定义
some_function.c:8:首先在这里定义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.