hpp/cpp 拆分全局函数:多重定义...错误

hpp/cpp split with global function: Multiple definition of ... error

编辑:问题是被遗忘的包含守卫。对不起!

因此我尝试应用两个文件规则,其中所有声明都进入 .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 包括在任何其他库或 executable-file、

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 中的函数创建一个环绕的 class 会起作用,但这并不能帮助我理解问题并添加一个冗余的命名空间,例如 lib1::lib1::addNumbers()

尝试在 .hpp 文件中使用 #define,如下所示

/* lib1.hpp */
#ifndef __LIB_1__
#define __LIB_1__
namespace lib1{
int addNumbers(int a, int b);
}
#endif /*__LIB_1__*/

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

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

正如 "Let Us Embed" 所说,使用预处理器指令来避免重复声明。

# pragma once ///if the compiler supports 

对于其他编译器使用:

#ifndef EXAMPLE
#define EXAMPLE
Add your code
#endif