编辑:问题是被遗忘的 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,例如 lib2、lib3,然后包含两者,lib2任何其他库或可执行文件中的 strong> 和 lib3,
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/