C++编译错误:多个定义"main",但项目中只有一个 main 函数

C++ compilation error: multiple definition of `main' but only 1 main function in project

本文关键字:main 项目 函数 有一个 编译 定义 C++ 错误      更新时间:2023-10-16

我在 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 找到多个主函数