我试图在单独的文件中正确声明和定义全局变量,并将它们包含在处理类声明的第三个文件中。
这三个文件是:
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
我使用全局变量dim
来声明和定义多维数组。我已在 global.h
中声明了 dim
并在 global.cpp
中定义了它。现在,我有一个名为 WorldState
的类,在其 header 中,我使用 dim
。如果我注释掉#include "global.cpp"
,它会抛出以下错误:
C:\Users\syamp\Documents\codeblocks\slam\WorldState.h|10|error: array bound is not an integer constant before ']' token
我的理解是,包含 .h
文件也包含相应的 .cpp
,并且所有声明都应位于 .h
内所有定义都应位于 .cpp
内。然而,在这种情况下它似乎不起作用。
1) 如果我决定将 global.cpp
文件包含在 WorldState.h
中,这不是不好的编程习惯吗?我正在尝试编写一个好的代码,而不仅仅是一个可以工作的代码。
2) 另一种方法是在 global.h
内定义变量 dim
(和 marker_num
)的值。这是好的编程习惯吗?
3)我相信我缺少一些东西。请建议解决此问题的最佳方法。我正在使用 codeblocks
和 C++11
。提前致谢。
最佳答案
I am using the global variable
dim
to declare and define a multidimensional array.
在编译时声明固定长度数组时,编译器必须知道其维度的值,但是您的分隔会阻止 的值编译器根本不知道dim
,因此dim
不能用于指定固定的数组维度。任何使用 dim
的代码都会编译成对其的引用,然后链接器将在编译完成后解析引用。仅仅因为 dim
被声明为 const
并不意味着它适合作为编译时常量。为此,您必须在其声明中定义其值,例如:
#ifndef GLOBAL_H_INCLUDED
#define GLOBAL_H_INCLUDED
static constexpr const int marker_num = 10;
static constexpr const int dim = (2 * marker_num);
using namespace std;
#endif // GLOBAL_H_INCLUDED
否则,如果将 dim
的声明和定义保存在单独的文件中,则必须在运行时动态分配数组,而不是在编译时静态分配。
I have declared
dim
insideglobal.h
and defined it insideglobal.cpp
.
对于运行时之前不需要使用的值来说,这很好。这不适用于您需要在编译时使用的值。
My understanding is that including the
.h
file includes the corresponding.cpp
as well
这根本不是事实。 project/makefile 在调用编译器时引入 .cpp
文件。 .h
文件与此无关。
that all declarations should be inside
.h
and all definitions should be inside.cpp
.
通常是的,但并非总是如此。
If I decide to include
global.cpp
file insideWorldState.h
, isn't it bad programming practice?
是的。
An alternative is to define values of variable(s)
dim
(andmarker_num
) insideglobal.h
. Is that good programming practice?
是的,如果您想在需要编译时常量的地方使用它们。
关于class - C++ - 在以下情况下,为什么我必须包含 .cpp 文件和/而不是 .h 文件才能访问全局变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42752144/