标头文件看不到全局变量

时间:2019-06-15 20:07:13

标签: c++

我有2个名为main.cpp和Volum_sumar.cpp的两个文件。我在main.cpp标头中包含了Volum_sumar.cpp,但在main.cpp中看不到全局变量 有人可以告诉我我的错误在哪里吗?

//main.cpp

#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <string>
#include <windows.h>
#include "Volum_sumar.cpp"
using namespace std;
fstream f("Figuri.txt");
fstream d("Dimens.txt");
int n=0;
struct Sfere
    {
      string codsf;
      char culoare [15];
      char material[15];
      float xc,yc,r,arie,volum;
    } sf[100],aux;
int main()
{
  cazul3();
}
// Volum_sumar.cpp
#include <iostream>
#include <fstream>
#include <cstring>
#include <cmath>
#include <string>
#include <windows.h>
using namespace std;
void cazul3(){
    double volt=0;
    for(int i=0;i<n;i++)
 {
     volt=volt+sf[i].volum;
}
cout<<"VOLUMUL SFERELOR INREGISTRARE ESTE DE :  "<<volt<<"cm3"<<endl;
}

1 个答案:

答案 0 :(得分:1)

您将要解决所有这些错误。

就像@CruzJean所说的那样,通过将Volum_sumar.cpp直接包含在main.cpp中,您正在尝试访问nsf,甚至还没有定义它们。

#include在其他cpp文件中添加cpp文件是错误的做法。您应该#include仅头文件。您应该在头文件中声明共享项目,以便cpp文件可以根据需要#include进行共享,然后分别编译cpp文件,最后将生成的目标文件链接在一起以构成最终的可执行文件。

需要跨一个cpp文件访问的全局变量需要在一个cpp文件中实例化,并在其他文件中声明为extern。链接器将解析extern引用。

请尝试以下类似操作:

shared.h

#ifndef shared_h
#define shared_h

#include <string>

struct Sfere {
    std::string codsf;
    char culoare [15];
    char material[15];
    float xc, yc, r, arie, volum;
};

extern Sfere sf[100];
extern int n;

#endif

main.cpp

#include <fstream>
#include "shared.h"
#include "Volum_sumar.h"

std::fstream f("Figuri.txt");
std::fstream d("Dimens.txt");
int n = 0;
Sfere aux;

int main() {
    cazul3();
}

Volum_sumar.h

#ifndef Volum_sumar_h
#define Volum_sumar_h

void cazul3();

#endif

Volum_sumar.cpp

#include <iostream>
#include "shared.h"
#include "Volum_sumar.h"

void cazul3() {
    double volt = 0;
    for(int i = 0;i < n; ++i) {
        volt = volt + sf[i].volum;
    }
    std::cout << "VOLUMUL SFERELOR INREGISTRARE ESTE DE : " << volt << "cm3" << std::endl;
}
相关问题