Sep 21, 2011

How to compile googletest with gcc and CMake on Mac OS X SnowLeopard

I often found the way with Visual Studio C++ or XCode on web but I don't use them on my laptop. So I researched the way without IDE.

My settings
  • Mac OS X 10.6.8(Snow Leopard)
  •  gcc 4.5.4
  • cmake 2.8.5
According to googletest's README, you need more than 2.6.4 of cmake but the version of gcc is not clear.

Process
  1. Get source code of google test from svn repository
  2. Build googletest with cmake
  3. Create source file that has main function
  4. Create test code
  5. Build test code with g++
  6. Run the test
(1) Get source code of google test from svn repository

Place the source where you want.
svn checkout http://googletest.googlecode.com/svn/trunk/ gtest-svn

(2) Build googletest with cmake
Make a directory that cmake runs, which is good for anywhere.  {GTEST_DIR} is where theres is googletest. It is success when you get libgtest.a and libgtest_main.a after build.

mkdir mybuild
cd mybuild
cmake ${GTEST_DIR}
make

(3) Create source file that has main function

Create source file that has main function. You can find sample as below link.

You have to call below functions in main function.
  • testing::InitGoogleTest(&argc, argv); 
  • RUN_ALL_TESTS();

#include <iostream>
#include "gtest/gtest.h"

GTEST_API_ int main(int argc, char **argv) {
  std::cout << "Running main() from testmain.cc\n";

  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
(4) Craeate test code
#include "gtest/gtest.h"

TEST(firstTest, abs)
{
  EXPECT_EQ(1, abs( -1 ));
  EXPECT_EQ(1, abs( 1 ));
}

(5) Build test code with g++
You have to add the directory where there is googletest's header file into include path. You also have to build test code with static library of google test that you made at (2).

As below, testmain.cc is a file that has main function and mytest.cc is a file that has test code.


g++ -I{GTEST_DIR}/include testmain.cc mytest.cc libgtest.a libgtest_main.a -o mytes

(6) Run the test
Run the test. It is success if you see the test result as below.




No comments:

Post a Comment