为了编写单元测试,我需要模拟静态库 libddrmgr.a 中的一些函数。我在 gtest_ddrmaint_cmds.cpp
上实现模拟代码并将其编译为 gtest_ddrmaint_cmds.o
。
但是g++在链接目标文件和静态库时提示多重定义错误:
g++ -g -o ddrmainttest main.o gtest_ddrmaint_cmds.o /walker/external/3rdparty/google/gtest.a /walker/external/3rdparty/google/gmock.a /walker/src/build/SLES/lib/libddrmgr.a -lacl -lxml2 -lpthread -ldl -luuid -lz -lresolv -lcap -lrt --coverage
/walker/src/build/SLES/lib/libddrmgr.a(ddrmgr.o): In function `DDR_Shutdown':
/walker/src/ddrmgr/ddrmgr.cpp:110: multiple definition of `DDR_Shutdown'
gtest_ddrmaint_cmds.o:/walker/src/gunittest/ddrmaint/gtest_ddrmaint_cmds.cpp:16: first defined here
/walker/src/build/SLES/lib/libddrmgr.a(ddrmgr.o): In function `DDR_Init':
/walker/src/ddrmgr/ddrmgr.cpp:38: multiple definition of `DDR_Init'
gtest_ddrmaint_cmds.o:/walker/external/3rdparty/google/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h:443: first defined here
collect2: ld returned 1 exit status
make: *** [ddrmainttest] Error 1
我还编写了一个演示程序来测试是否可以覆盖目标文件中的一些库拥有的函数并且它工作正常。有人能告诉我为什么上面会提示错误吗?谢谢!
最佳答案
为了模拟 C++ 中的函数,您不能简单地重新定义它们。正如您刚刚遇到的那样,这会导致多重定义
链接器错误。
按照理查德·霍奇斯 (Richard Hodges) 在他的评论中建议的方式进行,为您要使用的库函数编写一个薄包装器,并为这些包装器对象创建模拟。
在 Google Mock 中有很好的解释 docs :
It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).
Instead of calling a free function (say, OpenFile) directly, introduce an interface for it and have a concrete subclass that calls the free function:
class FileInterface { public: ... virtual bool Open(const char* path, const char* mode) = 0; }; class File : public FileInterface { public: ... virtual bool Open(const char* path, const char* mode) { return OpenFile(path, mode); } };
Your code should talk to FileInterface to open a file. Now it's easy to mock out the function.
关于c++ - 链接目标文件和静态库时出现多重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36614125/