C++编译错误:多个定义"main",但项目中只有一个 main 函数
C++ compilation error: multiple definition of `main' but only 1 main function in project
我在 lib 上工作,并基于 gtest 框架对其进行了单元测试。所以单元测试的设置编译得很好。但是,当我尝试稍微不同的设置来测量代码覆盖率时,编译失败并出现此错误:
[ 10%] Linking CXX executable coverageRun.exe
CMakeFiles/coverageRun.dir/tests/src/main.cpp.o: In function `main':
/cygdrive/d/code/tests/src/main.cpp:24: multiple definition of `main'
CMakeFiles/coverageRun.dir/CMakeFiles/3.6.3/CompilerIdCXX/CMakeCXXCompilerId.cpp.o:/cygdrive/d/code/cmake-build-debug/CMakeFiles/3.6.3/CompilerIdCXX/CMakeCXXCompilerId.cpp:514: first defined here
collect2: error: ld returned 1 exit status
make[3]: *** [CMakeFiles/coverageRun.dir/build.make:1215: coverageRun.exe] Error 1
make[2]: *** [CMakeFiles/Makefile2:101: CMakeFiles/coverageRun.dir/all] Error 2
make[1]: *** [CMakeFiles/Makefile2:113: CMakeFiles/coverageRun.dir/rule] Error 2
make: *** [Makefile:175: coverageRun] Error 2
这是我的main.cpp
文件的样子:
#include <iostream>
#include <gtest/gtest.h>
#include "helpers/helper.h"
#include "helpers/pathHelper.h"
namespace code{
bool isPreconditionsOK(){
auto testRoot = helper::readEnvVar(helper::path::TEST_ROOT);
bool result = true;
if(testRoot.empty()){
std::cerr << "Env. variable " << helper::path::TEST_ROOT
<< " should be set before test start." << std::endl;
result = false;
}
return result;
}
}
int main(int argc, char **argv) {
if(code::isPreconditionsOK()){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
};
}
那么我可以尝试什么来解决这个问题呢?
"CmakeCxxCompilerId.cpp"看起来像:link
我假设您在顶级目录中使用file(GLOB_RECURSE...
来获取项目的源代码列表。这种方法非常危险,你现在真的可以看到它,因为你陷入了麻烦。但作为解决方法,请尝试以下操作:
file(GLOB_RECURSE REMOVE_CMAKE "cmake-build-debug/*")
list(REMOVE_ITEM your_list_of_sources ${REMOVE_CMAKE})
这将解决您的直接问题,但您需要重新考虑一般方法以避免将来发生类似情况。
因为知道您在目录和编译器中的所有源代码中搜索只需找到 2 个主要函数,这当然是不允许C++世界中的。我提供给您的代码片段只是从编译中排除cmake-build-debug
文件夹中的代码。
看 https://public.kitware.com/Bug/view.php?id=11043使用类似这样的东西:
FILE(GLOB TARGET_H "${CMAKE_SOURCE_DIR}/*.h")
FILE(GLOB TARGET_CPP "${CMAKE_SOURCE_DIR}/*.cpp")
SET(TARGET_SRC ${TARGET_CPP} ${TARGET_H})
...
如果改用GLOB_RECURSE,它还将检查CMakeFiles文件夹和里面的内容。它将找到由cmake生成的具有main函数的cpp文件,这会导致"main"函数的多个定义。
>CMake 一定在你的项目中找到了另一个 *.cpp 文件,其中包含另一个 main()。 您应该修改 cmake 构建项目。检查此 cmake 找到多个主函数
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 代码块始终在项目中运行 main.cpp
- 如何将包含多个.cpp源文件的文件夹导入Eclipse项目中,每个源文件都有一个main()定义
- C++编译错误:多个定义"main",但项目中只有一个 main 函数
- 我正在使用Xcode进行c ++编程和学习。为什么我不能在一个项目中放置许多具有 MAIN 功能的单独源文件?
- main()函数位于.cpp文件中,该文件与我在c++中的项目同名
- SDL 项目的调试错误"没有可用于 main() 的源代码"
- 对于我的C ++项目,我在Eclipse中创建了子文件夹,如何将其包含在main中
- 在 Visual Studio 中调用 Python 中的C++项目 main()
- 在 Visual Studio 中多次运行 C++ 项目 main()
- 可视化 C++项目中的两个 main() 不会生成
- 项目文件夹c++中没有任何.cpp文件的main的多个定义
- 在VS2010上拥有多个项目和多个"main"功能
- Netbeans(C++)项目中的多个main()函数
- 使用QMake如何为每个main()构建一个项目
- C++:新建空项目(如何创建,添加main方法并打印"Hello, world")?