0
我是C++的新手。我正在尝试修改非常复杂的视频编解码器代码,作为我最后一年的学校项目的一部分。这是我的代码:C++全局变量未在此范围内声明
这是我已经声明了三个变量的extern头文件: yuv.h
#include <vector>
namespace X265_NS
{
extern int frameNumber;
extern int frameSize;
extern std::vector<int>numbers;
class YUVInput : public InputFile, public Thread
{
protected:
// some more variables
public:
// more variables and function declarations
};
}
这是一个使用这些变量的extern的第一个文件: yuv.cpp
#include "yuv.h"
//more includes
#include <vector>
using namespace X265_NS;
int frameNumber;
int frameSize;
std::vector<int>numbers;
// some stuff and function calls
// here I use my extern variables in a function
frameNumber = readCount.get();
frameSize = ceil((double)height/32) * ceil((double)width/32);
//more stuff
bool YUVInput::populateFrameQueue()
{
if(read<1)
{
ifstream file("/home/abu-bakr/bin/test.txt");
int number;
while (file >> number)
numbers.push_back(number);
}
}
// more stuff
这是我使用这些变量的extern第二类:
analysis.cpp
#include "yuv.h"
#include <vector>
....
using namespace X265_NS;
// some stuff
// its in a function and only place where I am using these variables
int qp_ctu = numbers.at((ctu.m_cuAddr + 1) + (frameSize*(frameNumber - 1)));
// more stuff
我想知道:
- 它是在yuv.h 文件我的extern变量的声明正确的地方?
- 如果我在两个cpp文件中定义这些变量,则会生成“已定义” 错误。如果我仅在一个类中定义它们,则“其他类中出现”未解决 外部符号“错误。
感谢您的回复
变化。 仍存在错误: 如何在我的cpp文件中定义矢量为“1 unresolved extern”变量错误正在生成。其次,当您告诉我在使用这些变量的后续类中使用上述解决方案时,但这会产生“已定义的错误”。 再次感谢您的帮助 –
我没有建议在“后续课程”中使用上述解决方案 - 我假定您指的是您正在复制多个编译单元中的定义。 C++中有“一个定义规则”。这意味着,在这种情况下,您不能在整个程序中多次定义变量。 – Peter
当我只在yuv.cpp中声明这些变量并且没有在分析中声明这些变量时,“未声明的标识符错误”正在产生。 请告诉我如何在cpp文件中定义向量。 –