为什么我这会报错?
报错:redefinition of 'int main()'// func.c文件
#include <stdio.h>
extern int count;
int main()
{
printf("count = %d\n", count);
return 0;
}
// text1.c文件
#include "func.c"
extern void func(void);
int count = 5;
int main(void)
{
func();
return 0;
} 问题出在你的代码中有两个不同的文件都定义了main函数。在C语言中,每个程序只能有一个main函数作为入口点。因此,你需要将其中一个main函数重命名为其他名称,或者将其放在另一个文件中。这样就可以解决这个redefinition的错误。 在你的代码中,出现了"redefinition of 'int main()'"错误,这是因为在 func.c 文件和 text1.c 文件中都定义了一个名为 main 的函数。在 C/C++ 中,每个程序只能有一个 main 函数作为入口点,因此定义多个 main 函数会导致重定义错误。
为了解决这个问题,你需要将其中一个文件中的 main 函数改名,例如改成其他名称比如 "main2"。这样就不会再出现重定义的问题了。
另外,使用#include "func.c"的方式包含源文件也是不推荐的做法。正确的方式是将函数声明包含在头文件中,然后在需要使用这些函数的文件中包含头文件即可。
下面是修改后的示例代码:
// func.h 文件
#ifndef FUNC_H
#define FUNC_H
extern int count;
void func(void);
#endif
// func.c 文件
#include <stdio.h>
#include "func.h"
int count = 5;
void func(void) {
printf("count = %d\n", count);
}
// text1.c 文件
#include "func.h"
int main(void) {
func();
return 0;
}
通过上述修改,你可以避免重定义 main 函数的问题,并且更规范地组织你的代码。希望我的回答能够帮到你。如有其他问题,欢迎继续提问。
页:
[1]