gpt4 book ai didi

c++ - 对全局数组的 undefined reference

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:12 25 4
gpt4 key购买 nike

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

undefined reference to `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) 机器人.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 中提供了这个定义。此外,当我在 Robot.cpp 中包含 #include "global.cpp" 时,它会起作用(但这不是可接受的做法)。所以,我相信这个错误是由于 global.cpp 没有正确链接。

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

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

最佳答案

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

关于c++ - 对全局数组的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42794141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com