I have an array called vel
declared inside global.h
and defined inside global.cpp
. When I try to use it inside a function, get_velocities()
, of another class called Robot
(inside Robot.cpp
), it says:
undefined reference to `vel'
Here are the three files:
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};
}
Edit:
I did read this question . What I realized was that the global variable requires not just a declaration but also a definition. I have provided this definition inside global.cpp
. Also when I include #include "global.cpp"
in Robot.cpp
, it works (But this is not an acceptable practice). So, I believe this error is due to global.cpp not linking properly.
1) Isn't it a common practice to declare global variables in global.h
and keep the definitions in global.cpp
? How do I link them properly? I believe that one way is to create a proper make
file. However, I am using codeblocks IDE
. How do I do it in this IDE?
2) Is it better to eliminate global.cpp
and do all definitions for global variables and functions inside the main
or the file that uses them?