【问题标题】:C++ compilation error: multiple definition of `main' but only 1 main function in projectC++ 编译错误:“main”的多个定义,但项目中只有 1 个 main 函数
【发布时间】:2017-05-20 14:27:23
【问题描述】:

我在开发 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

【问题讨论】:

标签: c++ compilation cmake googletest


【解决方案1】:

我假设您在顶级目录中使用file(GLOB_RECURSE... 来获取项目的源列表。这种方法非常危险,你现在真的可以看到它,因为你遇到了麻烦。但作为解决方法尝试这样的事情:

file(GLOB_RECURSE REMOVE_CMAKE "cmake-build-debug/*")
list(REMOVE_ITEM your_list_of_sources ${REMOVE_CMAKE})

这将解决您当前的问题,但您需要重新考虑通用方法以避免将来出现类似的情况。

因为你知道你在目录和编译器中搜索所有源代码只需要找到 2 个 main 函数,这在 C++ 世界中当然是不允许的。我提供给您的代码 sn-p 只是从编译中排除了 cmake-build-debug 文件夹中的代码。

【讨论】:

    【解决方案2】:

    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”函数的多个定义。

    【讨论】:

      【解决方案3】:

      CMake 必须在您的项目中找到另一个包含另一个 main() 的 *.cpp 文件。您应该修改 cmake 构建项目。 检查这个cmake finds more than one main function

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-23
      • 2017-04-18
      • 1970-01-01
      • 2016-07-13
      • 2017-07-11
      • 1970-01-01
      相关资源
      最近更新 更多