C++编译错误:`main'存在多个定义,但项目中只有一个主函数。

6

我正在开发一个库,并有基于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"看起来是这样的:链接


2
似乎是一个重复的问题,与https://dev59.com/k2Eh5IYBdhLWcg3wpE3w#22177285相同。 - Argenet
3
我会去查看CMakeCXXCompilerId.cpp文件的第514行。 - Jonas
@Jonas 这里有一个链接 https://repl.it/FBoX - silent_coder
当您使用GLOB_RECURSE时,最好使用外部构建。否则,CMakeLists.txt文件会因为大量的hack而变得丑陋。 - Aelian
3个回答

24

我假设你在顶层目录中使用 file(GLOB_RECURSE... 来获取项目源文件列表。这种方法非常危险,现在你可能已经遇到了问题。但是,作为解决方法,请尝试像这样做:

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

这将解决您眼前的问题,但您需要重新思考一般性的方法以避免将来出现类似的情况。

因为现在您正在整个目录中搜索所有来源,而编译器只是找到了两个主要函数,这在C++世界中当然是不被允许的。我向您提供的代码片段只是从编译中排除了cmake-build-debug文件夹中的代码。


5

看这个链接,可以使用类似以下的方法:

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" 函数的多次定义。

1
CMake必须在您的项目中找到另一个包含一个以上main()函数的*.cpp文件。您应该修改cmake构建项目。 请查看此cmake发现了多个main函数

最好在评论中链接到重复的内容,而不是在新答案中。这个问题似乎是cmake找到多个main函数的重复。 - cwschmidt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接