在c++中访问另一个文件中的vector或数组



我试图从另一个文件(pattern.cpp在这里)访问数组/向量的元素。根据这个讨论(http://cplusplus.com/forum/beginner/183828/)我应该做

//pattern.cpp
namespace myprogram {
void Pattern::FromReal()
{
extern std::vector<double> real_data;
for (auto it=real_data.begin(); it !=real_data.end(); it++)
std::cout<<" my vector "<< *it <<" ";
}
}
and the vector is here
//RealData.cpp
#include <vector>
std::vector<double> real_data{ 0., 0., 1.46, 1.51, 1.55, 1.58, 1.45, 1.48, 1.54, 1.54, 1.60, 1.56};

当我编译时,我得到这个错误

<directory>/x86_64/Gcc/gcc620_x86_64_slc6/6.2.0/x86_64-slc6/include/c++/6.2.0/bits/stl_iterator.h:770: undefined reference to `myprogram::real_data'
collect2: error: ld returned 1 exit status

我使用CMake和RealData.cpp已经添加到CMakeList。这里出了什么问题?我应该改变什么?

下面是工作示例。只需创建(如果还没有)一个realdata.h文件,其中real_data矢量的extern。然后你可以在pattern.cpp和任何你想要的real_data向量中包含这个标题,比如main.cpp。

main.cpp

#include <iostream>
#include "pattern.h"
#include "realdata.h"
extern std::vector<double> real_data;
int main()
{

std::cout<<"Size of vector from other file is: "<<real_data.size()<<std::endl;
myprogram::Pattern obj;
obj.FromReal();
return 0;
}

pattern.h

#ifndef PATTERN_H
#define PATTERN_H
namespace myprogram {

class Pattern 
{

public:
void FromReal();
};
}
#endif

pattern.cpp

#include "pattern.h"
#include "realdata.h"
#include <iostream>
namespace myprogram{
void Pattern::FromReal()
{

for (auto it=real_data.begin(); it !=real_data.end(); it++)
std::cout<<" my vector "<< *it <<" "<<std::endl;
}

}

realdata.h

#ifndef REALDATA_H
#define REALDATA_H
#include<vector>
extern std::vector<double> real_data;
#endif

realdata.cpp


#include "realdata.h"
std::vector<double> real_data{ 0., 0., 1.46, 1.51, 1.55, 1.58, 1.45, 1.48, 1.54, 1.54, 1.60, 1.56};

也不要忘记使用头保护