How to build and use GoogleTest shared library (.so) using g++ on Linux?

随声附和 提交于 2019-12-11 16:54:30

问题


NOTE it's not a duplicate of this question or this question.

How to build Googletest from source using g++ into a shared library (.so)?

I tried the steps described in Google Test's document on how to build a shared library, but linking the produced libgtest.so with my test programs didn't work - the linker throws tons of errors like:

"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&)' libgtest.so:gtest-all.cc:(.text+0x19bc4): first defined here ./libgtest.so: In function `testing::internal::TypedTestCasePState::VerifyRegisteredTestNames(char const*, int, char const*)':

When building libgtest.so, I used command:

g++ -fPIC -DGTEST_CREATE_SHARED_LIBRARY=1 -pthread -c $(GTEST)/src/gtest-all.cc -shared (this macro is required in the aforementioned Google Test's document) and then mv gtest-all.o libgtest.so

When linking with libgtest.so, I used load flag -DGTEST_LINKED_AS_SHARED_LIBRARY=1, as recommended in the aforementioned Google Test's document. I also used -L flag to tell g++ where the library is.

NOTE: if I choose to build a libgtest.a archive from source and link my test program with this archive, everything is fine (instructions on how to build it is also in that Google Test document). The reason why I'd like to switch from libgtest.a to libgtest.so is I want the executables to load GoogleTest at runtime so linking might be faster.


回答1:


Here is the solution I found.

step 1. build object file gtest-all.o

g++ -fPIC -isystem ../path/to/googletest/include -I../utils/third-party/googletest/ -pthread -c ../path/to/googletest/src/gtest-all.cc

It's recommended by GoogleTest's doc to add a macro flag -DGTEST_CREATE_SHARED_LIBRARY=1 to the command above.

step 2. compile shared library

g++ -fPIC -shared gtest-all.o -o libgtest.so

Then, to link against the shared library

Be sure to use -Wl,-rpath=./path/to/libgtest.so flag. There is no white space between -Wl, and -rpath (-Wl,option means passing option to linker. more on -Wl,option). It's recommended to add flag -DGTEST_LINKED_AS_SHARED_LIBRARY=1.



来源:https://stackoverflow.com/questions/51815686/how-to-build-and-use-googletest-shared-library-so-using-g-on-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!