lundi 13 mars 2017

C++ - Why do I have to include .cpp file along with/ instead of .h file to acces the value of a global variable in the following case?

I am trying to properly declare and define global variables in separate files and include them in a third file which deals with class declaration.

The three files are:

1) global.h

#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED

extern const int marker_num;
extern const int dim;

using namespace std;

#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"   

constexpr const int marker_num = 10;
constexpr const int dim = (2 * marker_num) + 3;

3) WorldState.h

#ifndef WORLDSTATE_H
#define WORLDSTATE_H
#include "global.h"
#include "global.cpp"

class WorldState{

    public:
        WorldState(float a[], float b[dim][dim]);
        get_wstate();

    protected:

    private:
        float w_state[];
        float covar_matrix[dim][dim];    
};

#endif // WORLDSTATE_H

I am using the global variable dim to declare and define a multidimensional array. I have declared dim inside global.h and defined it inside global.cpp. Now, I have a class called WorldState and inside its header, I am using dim. If I comment out #include "global.cpp", it throws the following error:

C:\Users\syamp\Documents\codeblocks\slam\WorldState.h|10|error: array bound is not an integer constant before ']' token

My understanding is that including the .h file includes the corresponding .cpp as well, and that all declarations should be inside .h and all definitions should be inside .cpp. However, it doesn't seem to work in this case.

1) If I decide to include global.cpp file inside WorldState.h, isn't it bad programming practice? I am trying to write a good code not just a code that works.

2) An alternative is to define values of variable(s) dim (and marker_num) inside global.h. Is that good programming practice?

3) I believe there is something that I am missing. Kindly suggest the best method to resolve this issue. I am using codeblocks and C++11. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire