首页 > 解决方案 > 从 C++ 中的另一个文件访问向量或数组

问题描述

我正在尝试从另一个文件(此处为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 中。这里有什么问题?我应该改变什么?

标签: c++arraysvectorcmake

解决方案


是工作示例。只需创建(如果还没有)一个包含向量的 realdata.hextern文件real_data。然后你可以在 pattern.cpp 和任何你想要这个real_data向量的地方包含这个头文件,比如在 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;
}

模式.h

 #ifndef PATTERN_H
#define PATTERN_H
namespace myprogram {
    
    class Pattern 
    {
        
    public:
        void FromReal();
    };
}
#endif

模式.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;
        }
        
}

真实数据.h

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

真实数据.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};

也不要忘记使用头卫


推荐阅读