【发布时间】: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++