【问题标题】:c++ compiler error multiple definition of a variable [duplicate]c ++编译器错误多个变量定义[重复]
【发布时间】:2016-06-05 23:59:12
【问题描述】:

我正在努力学习 C++ 语言(请容忍我的菜鸟)。 在遵循几本书中的教程后,我决定尝试使用标题

我有一个名为 Untitled2.cpp 的文件,其中包含

#include <iostream>
#include "findaverage.h"
#include <string>
using namespace std;

int main(){
cout<<find_average();
}

一个名为 findaverage.h 的头文件,其中包含

#ifndef FINDAVERAGE_H
#define FINDAVERAGE_H
int find_average();
double first_no;
double second_no;
#endif

和一个 findaverage.cpp 文件,其中包含

#include "findaverage.h"
#include <iostream>
using namespace std;
int find_average(){
std::cout << "Enter a number"<<endl;
std::cin>>first_no;
std::cout<<"Enter another number"<<endl;
std::cin>>second_no;
return (first_no+second_no)/2;
};

当我在 Code::Blocks 中编译程序时,出现以下错误

||=== Build: Debug in test (compiler: GNU GCC Compiler) ===|
obj/Debug/Untitled2.o||In function `main':|
/root/Untitled2.cpp|7|multiple definition of `second_no'|
obj/Debug/findaverage.o:/root/findaverage.cpp|5|first defined here|
||error: ld returned 1 exit status|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

我正在尝试遵循类似于这张图片的方法

问题:如何成功解决实验代码中的多重定义问题?

【问题讨论】:

  • 1.使用using namespace std; 不是一个好主意 2. 除非迫不得已,否则请勿发布图片
  • 为什么double first_no; double second_no;在头文件中
  • 我猜你正在尝试使用全局变量——这也是个坏主意
  • @Ed Heal..我认为我们可以把它放在标题中?我正在查看图片中的快照并进行实验......但我不能说我哪里出错了。
  • 不要使用全局变量。将它们放入 .cpp 文件和函数内部

标签: c++


【解决方案1】:

问题在于您包含一个带有 定义 全局变量的标题。标头应该只包含声明,而不是定义:

#ifndef FINDAVERAGE_H
#define FINDAVERAGE_H
int find_average();
extern double first_no;
extern double second_no;
#endif

但是,这将无法构建并出现不同的错误,因为您需要在您的一个 cpp 文件中为您的变量提供定义 - 例如,在 Untitled2.cpp 中:

#include <iostream>
#include "findaverage.h"
#include <string>
using namespace std;

int main(){
    cout<<find_average();
}

double first_no;
double second_no;

请注意,如果您不需要将这些变量设为全局变量,则可以将它们设置为函数的本地变量,或 cpp 文件的本地变量。

【讨论】:

  • 这似乎解决了问题,但我在 findaverage.cpp 中收到另一个错误“未定义对 first_no 的引用”
  • @repzero 您是否已将定义添加到您的Untitled2.cpp,如上所示?
  • 优秀!!!!!!我想我现在明白了……我需要在 extern 上阅读更多内容……我注意到了,但从来没有在精神上掌握它...
  • @repzero 与 extern 的处理非常简单。我想你已经看到函数与原型发生了什么 - 即标头具有没有主体的声明,这使其成为声明,而 cpp 再次具有标头加上主体,这使其成为定义。无论哪种方式,变量都没有“主体”,所以extern 说“这是一个没有主体的变量”,即承诺在其他地方有一个同名的变量。在 cpp 文件中声明的同一个变量提供了“body”,以便链接器可以找到它。
  • ..感谢您为我打破这个事实..:D
【解决方案2】:

把头文件改成

#ifndef FINDAVERAGE_H
#define FINDAVERAGE_H
int find_average();
// No - wrong place double first_no;
// No - wrong place double second_no;
#endif

因为变量将包含在头文件位于 .cpp 文件中的任何位置

把函数改成这个

int find_average(){
  double first_no;
  double second_no;

   std::cout << "Enter a number"<<endl;
   std::cin>>first_no;
   std::cout<<"Enter another number"<<endl;
   std::cin>>second_no;
   return (first_no+second_no)/2;
};

应添加错误检查以防用户不输入数字 - 但我将其留给读者

【讨论】:

  • Gr8...看起来很简单,很到位
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-25
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 2010-09-07
  • 2022-11-12
相关资源
最近更新 更多