You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++链接器报错‘multiple definition of `main'’原因及解决咨询

问题:C++链接器报错multiple definition of main的原因是什么?

近日运行C++程序时,链接器报错multiple definition of main。此前文件名为Main.cpp时程序可正常运行,更换文件名后出现该错误,且曾参考视频修改过编译器设置,无法理解错误信息。

相关代码

#include <iostream> //iostream allow us to load pre-built libraries.

int main() // main function. Function in c++ is a block of code that does many things.
{
    std::cout << "Hello World ! This is my first C++ project" << std:: endl;
    std::cout << "This is Anish Sharma";
    return 0;
}

编译操作

Terminal -> Run Task... -> GCC compiler.

终端报错信息

* Executing task: Build with GCC compiler 14.2, released [1.8.2024]

Starting build...
cmd /c chcp 65001>nul && C:\mingw64\bin\g++.exe -g -std=c++2b C:\Users\ANISH\Documents\CPP\*.cpp -o C:\Users\ANISH\Documents\CPP\rooster.exe
C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\ANISH\AppData\Local\Temp\ccME9uEU.o: in function `main':
C:/Users/ANISH/Documents/CPP/new.cpp:3: multiple definition of `main'; C:\Users\ANISH\AppData\Local\Temp\cce2cCLP.o:C:/Users/ANISH/Documents/CPP/main.cpp:2: first defined here
C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/14.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\ANISH\AppData\Local\Temp\ccup70G8.o: in function `main':
C:/Users/ANISH/Documents/CPP/numbersprinting.cpp:4: multiple definition of `main'; C:\Users\ANISH\AppData\Local\Temp\cce2cCLP.o:C:/Users/ANISH/Documents/CPP/main.cpp:2: first defined here
collect2.exe: error: ld returned 1 exit status

Build finished with error(s).

* The terminal process terminated with exit code: -1.
* Terminal will be reused by tasks, press any key to close it.

错误原因

你的编译命令使用了C:\Users\ANISH\Documents\CPP\*.cpp,这会把该目录下所有.cpp文件都编译并链接成一个可执行程序。从报错信息可以明确看到,目录里的main.cpp、new.cpp、numbersprinting.cpp三个文件中都定义了main()函数。

C++程序的规则是:一个程序只能有一个main函数作为入口点。当多个文件都包含main函数时,链接器无法确定使用哪个作为程序的起始执行点,因此抛出multiple definition of main错误。

之前文件名是Main.cpp时能正常运行,大概率是当时的编译命令仅针对单个文件(比如只编译Main.cpp),或者目录中没有其他包含main函数的.cpp文件。修改文件名后,编译命令变成批量处理所有.cpp文件,就触发了多个main函数的冲突。


内容的提问来源于stack exchange,提问作者Anish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:35:15