gpt4 book ai didi

C++ 编译错误 : multiple definition of `main' but only 1 main function in project

转载 作者:太空狗 更新时间:2023-10-29 23:43:47 25 4
gpt4 key购买 nike

我在 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 文件夹中的代码从编译中排除。

关于C++ 编译错误 : multiple definition of `main' but only 1 main function in project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41495301/

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