【发布时间】:2021-11-27 04:33:16
【问题描述】:
我正在尝试从另一个文件(此处为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。这里有什么问题?我应该改变什么?
【问题讨论】:
-
你也能展示你的 CMakeList 吗?您是否将头文件或 cpp 文件包含到
pattern.cpp? -
@mrq1901 查看我的回答中给出的工作示例。只需创建(如果还没有)一个 realdata.h 文件,其中包含
real_data向量的外部。然后,您可以在 pattern.cpp 中包含此标头,以及在 main.cpp 中包含此real_data向量的任何位置。 -
从错误信息中可以看出,它指的是
myprogram::real_data:命名空间myprogram中real_data的定义。您的RealData.cpp文件定义了real_data在任何命名空间之外。