gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:55:33 25 4
gpt4 key购买 nike

场景:

在 Netbeans IDE 中使用以下两个文件创建的 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;
}

新主.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程序中头文件的需要时,我尝试了上面的应用程序(原样)。它被编译并给出如下输出

Entered Value is = 4200800 & 102
Entered Value is = 1 & 102
Entered Value is = 1 & 2

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

关于头文件的使用,我遇到了这个 link那里说,我们可以使用 #include 包含 C 文件本身。因此,我在文件 newmain.c

中使用了以下行
#include "some_function.c"

正如预期的那样,它显示了以下错误

error: too few arguments to function 'function_1()'
error: too few arguments to function 'function_1(1)'

此外,我还遇到了以下(意外)错误:

some_function.c:8: multiple definition of `function_1'
some_function.c:8: first defined here

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

最佳答案

您可能正在使用 C 的 C 99 之前的方言,它具有“隐式函数声明”。这意味着没有声明的函数被认为具有这种签名:

int function_1();

即返回一个 int 并接受任意数量的任意类型的参数。当您传递与您的函数定义不兼容的参数列表时,您会在运行时调用未定义的行为

关于多重定义错误,想一想。您包含的每个翻译单元 some_function.c 都有自己的函数定义。就好像您在每个其他 .c 文件中都写了该定义一样。 C 不允许在一个程序/库中有多个定义。

关于c - 在#Include 指令中使用 C 文件时 C 程序出错(多重定义错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31759700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com