c++ - hpp/cpp split with global function : Multiple definition of . .. 错误

标签 c++ c++11 linker prototype header-files

编辑:问题是被遗忘的 include guard。抱歉!

因此我尝试应用两个文件规则,其中所有声明都进入 .hpp 文件,所有定义进入相应的 .cpp 文件。我的问题是库中的全局函数,其 header 包含在多个位置。
例如:

/* lib1.hpp */
namespace lib1{
int addNumbers(int a, int b);
}

和cpp文件:

/* lib1.cpp */
namespace lib1{
int addNumbers(int a, int b) {return a + b;}
}

现在,如果我在多个库中包含 lib1.hpp,例如 lib2lib3,然后包含两者,lib2lib3

I get the multiple definitions of addNumbers() error.

这对我来说很有意义,但我不知道如何解决这个问题。我尝试了 extern关键字,但它不会改变任何东西:

/* lib1.hpp */
namespace lib1{
extern int addNumbers(int a, int b);
}

并且 cpp 文件保持不变:

/* lib1.cpp */
#include "lib1.hpp"

namespace lib1{
int addNumbers(int a, int b) {return a + b;}
}

如果我为 lib1.hpp 中的函数创建一个外围类,它会起作用,但这并不能帮助我理解问题并添加一个冗余的命名空间,如 lib1::lib1::addNumbers()例如。

最佳答案

1.) 如果您的函数应该在头文件中定义,请添加 inline 关键字。

2.) 我认为以两个下划线开头的名称是为编译器保留的。

关于c++ - hpp/cpp split with global function : Multiple definition of . .. 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35983598/

相关文章:

c++ - 如何将字符串数字转换为单个数字的 int 数组

c++ - 在类声明中定义静态变量时未解析的外部符号

c++ - 如何递归使用typedef?

c++ - 为什么在返回兼容类型时需要显式 std::move?

c++ - Visual Studio 2015 curl 不会静态链接

linux - 关于静态链接程序的 MMU 和 gcc 的默认链接器文件

c++ - Windows 平台最快的 C++ 链接器是什么?

c++ - 从不同线程调用 recvfrom() 和 setsockopt() 添加/离开多播成员

c++ - 在多个cpp文件中包含带有定义的h文件

C++ - 我应该接受什么类型的参数? (什么时候投?)