Google's C++ Test Framework has two output libraries: one is gtest.lib and the other one is gtest_main.lib. According to Nik Reiman's answer on how to setup gtest with Visual Studio, we should link to gtest_main.lib but I'm linking to gtest.lib and the sample test cases that I have are running fine.
What's the difference between the two libraries and does it matter which one I link to?
In fact, the various build methods available for googletest don't build the libraries consistently. At least this part is consistent though:
gtest
The gtest library (variously called
gtest.a
,gtest.so
,gtest.lib
orlibgtest.a
, etc, depending on your platform and whether you are using the shared library) contains the object code for the gtest framework, including everything that tests need. Basically it implements everything you can use fromgtest/gest.h
. It does not include amain()
method.gtest_main
It includes a trivial main method that will launch the registered tests, something like this (as of 1.8):
Now the inconsistent part is that
gtest_main
sometimes also includes everything fromgtest
, so that you only need to link against eithergtest
(if you want to write your ownmain()
method) orgtest_main
(if you want the use the canned main method above). This is the case, for example, if you use theMakefile
build included ingoogletest/make
:Clearly,
gtest_main.a
includes everything thatgtest.a
does, plus thegtest-main.o
object which includes the main function.With the CMake build, however, the situation is different, at least for some build artifacts. For example, for the main libraries we have:
Here,
gtest_main
only contains the main function and nothing much else1. Thetarget_link_libraries
line tells anything else using this CMake build that if you linkgtest_main
you should also linkgtest
, so in the rest of the file it is common to see things linked only againstgtest_main
. Indeed, the documentation earlier in theCMakeLists.txt
file makes this explicit:Note the "with one one them" part. What they really mean is that if you are building with this same CMake system you can do that, but at the actual link level you need both
libtest.a
andlibgtest_main.a
or else you won't pull in what you need to write a test.1 Indeed, with CMake libgtest.a ends up at 1,755,216 bytes, and libgtest_main.a is only a paltry 3,836 bytes. With the
../make/Makefile
build, those figures are 3,365,240 and 3,398,356 respectively. Evidently there are differences beyond the files included that blow up the size of theMakefile
version.the only reasonable difference is that gtest_main.lib provides a default implementation of a test application entry point (i.e.
main
function):Citation from Getting started with Google C++ Testing Framework:
If you want to write your main function yourself - you should link with gtest.lib.
You will need to link
gtest.lib
to your project with the unit tests.