title: How to build and use GoogleTest shared library (.so) using g++ on Linux?
body: <blockquote>
    <p><strong>NOTE</strong> it's not a duplicate of <a href="https://stackoverflow.com/questions/13513905/how-to-setup-googletest-as-a-shared-library-on-linux">this question</a> or <a href="https://stackoverflow.com/questions/42643002/build-google-test-like-shared-library">this question</a>.</p>
  </blockquote>
  
  <p>How to build Googletest <strong>from source</strong> using g++ into a shared library (.so)?</p>
  
  <p>I tried the steps described in <a href="https://github.com/google/googletest/blob/master/googletest/README.md#as-a-shared-library-dll" rel="nofollow noreferrer">Google Test's document</a> on how to build a shared library, but linking the produced <code>libgtest.so</code> with my test programs didn't work - the linker throws <em>tons</em> of errors like:</p>
  
  <blockquote>
    <p>"gtest-all.cc:(.text+0x19b50): multiple definition of `testing::internal::HasNewFatalFailureHelper::~HasNewFatalFailureHelper()'libgtest.so:gtest-all.cc:(.text+0x19b50): first defined here
    ./libgtest.so: In function `testing::internal::HasNewFatalFailureHelper::~HasNewFatalFailureHelper()':"
    gtest-all.cc:(.text+0x19bc4): multiple definition of `testing::internal::HasNewFatalFailureHelper::ReportTestPartResult(testing::TestPartResult const&amp;)'
    libgtest.so:gtest-all.cc:(.text+0x19bc4): first defined here
    ./libgtest.so: In function `testing::internal::TypedTestCasePState::VerifyRegisteredTestNames(char const*, int, char const*)':</p>
  </blockquote>
  
  <p>When building <code>libgtest.so</code>, I used command:</p>
  
  <p><code>g++ -fPIC -DGTEST_CREATE_SHARED_LIBRARY=1 -pthread -c $(GTEST)/src/gtest-all.cc -shared</code> (this macro is required in the aforementioned Google Test's document) and then <code>mv gtest-all.o libgtest.so</code></p>
  
  <p>When linking with <code>libgtest.so</code>, I used load flag <code>-DGTEST_LINKED_AS_SHARED_LIBRARY=1</code>, as recommended in the aforementioned Google Test's document. I also used <code>-L</code> flag to tell g++ where the library is.</p>
  
  <p><strong>NOTE:</strong> if I choose to build a <code>libgtest.a</code> archive from source and link my test program with this archive, everything is fine (instructions on how to build it is also in that <a href="https://github.com/google/googletest/blob/master/googletest/README.md#build" rel="nofollow noreferrer">Google Test document</a>). The reason why I'd like to switch from <code>libgtest.a</code> to <code>libgtest.so</code> is I want the executables to load GoogleTest at runtime so linking might be faster.</p>