Search code examples
c++visual-studiogoogletest

"_main already defined" while using gtest


I have a solution with two projects in it

One of them is a console application, and the other one is a Google Test project

My project has a .h file and a .CPP with a main() in it

My gtest consists of a .CPP file which calls the .h file using #include and a main function to RUN_ALL_TESTS()

I need a main in my project but I also need a main in the gtest project, but having two main() doesn't let me build the gtest successfully

Is there a workaround to this? Sorry if it's a silly question, I have no clue how to use gtest because various sites keep presenting different ways


Solution

  • First of all you should have a dedicated file main.cpp for your main() function, which contains nothing else.

    E.g. your project structure could look like:

    • project1
      • file1.h
      • file1.cpp
      • main.cpp

    I'm not familiar wiht gtest specifically, but usually unit test frameworks have a separate file for the gtest main function, e.g. gtest_main.cpp. Tests are in one or more files like file1test.cpp etc.

    So you would compile and link your project1 with file1.h, file1.cpp and main.cpp to get an executable.

    For unit tests you would compile and link file1.h, file1.cpp, file1test.cpp and gtest_main.cpp for a unit test executable.

    Structure could be like

    • project1
      • file1.h
      • file1.cpp
      • main.cpp
    • project1test
      • file1test.cpp
      • gtest_main.cpp

    EDIT additional infos on linking:

    In project1test you would include file1.h with #include "../project1/file1.h".

    For correct linking right-click on project1test project

    --> Configuration Properties --> Linker --> Input --> Additional Dependencies --> Add "..\project1\Debug\file1.obj"

    As @Alan Birtles pointed out it would be even more clearer if you had the following structure:

    • project1library
      • file1.h
      • file1.cpp
    • project1application
      • main.cpp
    • project1test
      • file1test.cpp
      • gtest_main.cpp

    The you would get a static/dynamic library project1library.lib/.dll, an executable project1application.exe and a unit test executable project1test.exe.

    The advantage is that you would just link the library in your unit test project with

    --> Configuration Properties --> Linker --> Input --> Additional Dependencies --> Add "..\project1library\Debug\project1library.lib"

    If you have more than one file you need from your project, you don't have to add every obj file, but just one lib file.

    But making sure that everything was rebuilt correctly on changes can be more difficult and error prone with a lib, an executable and a unit test project.