从 C++ 中的另一个文件访问向量或数组

Access a vector or an array from another file in C++

我正在尝试从另一个文件(此处为 pattern.cpp)访问 array/vector 的元素。根据这个讨论(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。这里有什么问题?我应该改变什么?

Here 是工作示例。只需创建(如果还没有的话)一个 realdata.h 文件,其中包含 real_data 向量的 extern。然后你可以只在 pattern.cpp 中包含这个 header 以及你想要这个 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};

另外别忘了使用header guards