c++ - 为什么包含标题时出现多个定义错误?
问题描述
我声明了一个包含函数 声明的Algebra.h
文件:add()
#ifndef Algebra_
#define Algebra_
namespace Algebra{
int add(int x, int y);
}
#endif
然后我实现add()
为:
代数.cpp
#include "Algebra.h"
namespace Algebra{
int add(int x, int y){
return x+y;
}
}
然后我有A类和B类,其中包括Algebra.h
:
溴化氢
#ifndef B_
#define B_
#include "Algebra.h"
#include <iostream>
class B{
public:
void func(int x, int y);
};
#endif
B.cpp
#include "B.h"
void B::func(int x, int y){
int val = Algebra::add(x,y);
std::cout << "B : "<< val << std::endl;
}
啊
#ifndef A_
#define A_
#include <iostream>
#include "Algebra.h"
#include "B.h"
class A{
public:
void func(int x, int y);
};
#endif
A.cpp
#include "A.h"
void A::func(int x, int y){
int val = Algebra::add(x,y);
std::cout << "A : " << val << std::endl;
}
主文件
#include "A.h"
#include "B.h"
#include "Algebra.h"
int main(){
A a;
B b;
a.func(3,4);
b.func(3,4);
int val = Algebra::add(3,4);
std::cout << "main : " << val << std::endl;
}
我尝试使用编译
g++ A.cpp B.cpp main.cpp -o bin
g++ A.cpp B.cpp Algebra.cpp main.cpp -o bin
我收到此错误:
/tmp/ccBXhev4.o:在函数'Algebra::add(int, int)'中:main.cpp:(.text+0x0):'Algebra::add(int, int)'的多重定义/tmp/ccfaCF5H .o:A.cpp:(.text+0x0): 首先在这里定义 collect2: error: ld returned 1 exit status
add()
我什至尝试将函数内联在中Algebra
,但仍然出现错误。我也不想让代数成为一门课。
为什么即使我添加了代数头文件,我也会收到多重定义错误,并且它没有定义而只是声明?
解决方案
推荐阅读
- windows - 是否可以使用脚本或 ansible 本身直接在目标主机上调用 ansible 或 ansible-playbook?
- java - Mono 的 doOnSuccess 与 doOnNext 之间有区别吗?
- c# - 为什么价值不想改变?
- sqlite - How can insert Cutout sign ( ' ) sqlite database from a txt file
- wpf - 鼠标双击带有电子表格的用户控件上的 windowsformhost
- reactjs.net - 孩子呼叫祖父母功能
- javascript - 使用 Javascript 动画可变字体
- instagram - Instagram autolikers 如何绕过 API 弃用?
- python - TypeError: 'datetime.datetime' 对象不支持索引
- cuda - 用 cuda.jit 装饰器替换 njit 装饰器