c++ - 链接目标文件和静态库时出现多重定义错误

标签 c++ g++ googletest

为了编写单元测试,我需要模拟静态库 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/

相关文章:

c++ - 在 Mac OS 10.6 上使用 boost::xpressive 编译时间过长

c++ - gtest 的 undefined reference

c++ - 难以实现对每行 C++ 上打印的整数数量的限制

c++ ->?= 运算符是什么意思?

c++ - 为什么 Visual C++ 无法编译继承自私有(private)嵌套类的友元模板?

c++ - 这些 g++ "multiple definition"错误是怎么回事?

c++ - 对于 double 或 float 的总和,EXPECT_EQ 出错

c++ - 我怎么能期望谷歌测试多次失败?

c++ - "Principles and Practice Using C++"第6.3.1章代码错误?

C++ 字符串.c_str()