首页 > 解决方案 > 为什么包含标题时出现多个定义错误?

问题描述

我声明了一个包含函数 声明的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;
}

我尝试使用编译

  1. g++ A.cpp B.cpp main.cpp -o bin

  2. 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,但仍然出现错误。我也不想让代数成为一门课。

为什么即使我添加了代数头文件,我也会收到多重定义错误,并且它没有定义而只是声明?

标签: c++

解决方案


推荐阅读