未定义的全局数组引用

时间:2017-03-14 18:46:31

标签: c++ arrays global-variables

我在vel内声明了一个名为global.h的数组,并在global.cpp内定义。当我尝试在名为get_velocities()的另一个类(Robot内)的函数Robot.cpp中使用它时,它会说:

  

未定义对`vel'的引用

以下是三个文件: 1)global.h

#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
#include <array>

using std::cout;
using std::cin;
using std::endl;
using std::array;

static constexpr const int marker_num = 10;
static constexpr const int dim = (2 * marker_num) + 3;
extern array <float, 3> vel;

#endif // GLOBAL_H_INCLUDED

2)global.cpp

#include <iostream>
#include <cstdio>
#include <cmath>
#include "global.h"
#include "WorldState.h"
#include "Robot.h"
#include "Sensor.h"
#include "Marker.h"

array <float, 3> vel = {0.0, 0.0, 0.0};

3)Robot.cpp

#include <iostream>
#include <cstdio>
#include <cmath>
#include "global.h"
#include "WorldState.h"
#include "Robot.h"
#include "Sensor.h"
#include "Marker.h"


Robot::Robot(float a, float b, float c){

    //ctor
    x = a;
    y = b;
    theta = c;
}

void Robot::get_velocities(){

    v_tx = 1.0;
    v_ty = 0.0;
    omega_t = 0.0;

    vel = {v_tx, v_ty, omega_t};

}

修改

我确实读过这个question。我意识到全局变量不仅需要声明,还需要定义。我在global.cpp内提供了这个定义。此外,当我在#include "global.cpp"中加入Robot.cpp时,它也有效(但这不是一种可接受的做法)。所以,我认为这个错误是由于global.cpp没有正确链接。

1)在global.h中声明全局变量并将定义保留在global.cpp中是不是通常的做法?如何正确链接它们?我相信一种方法是创建一个合适的make文件。但是,我正在使用codeblocks IDE。我该如何在这个IDE中完成它?

2)最好是消除global.cpp并对main或使用它们的文件中的全局变量和函数进行所有定义吗?

2 个答案:

答案 0 :(得分:0)

vel中声明并定义数组global.h。也许将它们存储在同一个类中会有所帮助。

答案 1 :(得分:0)

我的问题是Codeblocks IDE没有关联global.cpp。我找到了答案here(第一个答案)。如果这个问题是重复或重复的组合,我会道歉。