gpt4 book ai didi

c - "Linking Error: Duplicate public_main in module"构建时

转载 作者:行者123 更新时间:2023-11-30 21:18:36 24 4
gpt4 key购买 nike

我在一个工作区下创建了一个简单的文件,构建并成功执行。并再次在同一工作区下创建另一个文件。我收到链接错误,例如:

"====Linking===== Error: Duplicate public_main in module...."在构建时,当我尝试执行第一个文件时,我也遇到了相同的错误。

请查看下面的代码并提出建议。

文件1:n_numbers.c

#define N 10

main()
{

int count;
float sum, number;

count=0;
sum=0;

printf("Enter 10 numbers to calculate the Sum");

while(N<10)
{
scanf("%f", &number);

sum=sum+number;

count=count+1;
}

printf("sum=5.2%", sum);
}

文件2:two.numbers.c

main()
{

int a,b,c;

printf("Enter Two numbers for a and b\n");
scanf("%d %d",&a, &b);

c=a+b;

printf("c=%d", c);

}

最佳答案

我怀疑你的问题是:

gcc file_a.c
a.out

作品

gcc file_b.c
a.out

作品

gcc file_a.c file_b.c

linker error

因为 gcc 正在尝试创建单个可执行文件,并且每个可执行文件必须恰好有一个 main 函数。

如果 file_a 和 file_b 定义了一个名为 public_main 的函数,那么问题就变成了在任何给定的调用中要使用哪个函数 - C 通过一个简单的规则解决了这个问题 - 每个可执行文件中的每个函数只能一个

注意其他语言有不同的规则,C++ 可以有多个具有相同名称但不同原型(prototype)的函数(重载),或者在不同的类(命名空间)内,它实际上通过所谓的名称修改来实现这两个功能。 Python 使用命名空间和复杂的作用域规则等。

从评论中复制!

Hi Steve, I had only one main() in each executable, but still i am getting same error – user2714972

You have 2 .c files and you are linking them into a single executable, (.exe), that is what gcc does when you give it more than one .c file if you would like to make 2 executables you need to call gcc twice, once with each .c and with -o differcent_exe_name to stop both being called a.out or a.exe – Steve Barnes

如果正如某些人所建议的那样,您正在使用 IDE,则需要创建单独的项目或根据 IDE 指定单独的目标。

关于c - "Linking Error: Duplicate public_main in module"构建时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18426621/

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