【问题标题】:c++ global variable was not declared in this scopec++ 全局变量未在此范围内声明
【发布时间】:2017-08-19 01:10:51
【问题描述】:

我是 C++ 新手。作为我最后一年学校项目的一部分,我正在尝试修改一个非常复杂的视频编解码器代码。这是我的代码:

这是我声明了三个外部变量的头文件: 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

};
}

这是第一个使用这些外部变量的文件: 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

这是我使用这些外部变量的第二个类:

分析.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 中声明我的外部变量是否合适? 文件?
  • 如果我在两个 cpp 文件中定义这些变量,“已定义” 产生错误。如果我只在一个类中定义它们,“未解决 外部符号”错误出现在其他类中。

【问题讨论】:

    标签: c++ scope extern


    【解决方案1】:

    问题出在你的 yuv.cpp 中

    using namespace X265_NS;
    int frameNumber;
    int frameSize;
    

    这些定义是::frameNumber::frameSize,与X265_NS::frameNumberX265_NS::frameSize 不同。

    把上面改成

    namespace X265_NS {
        int frameNumber;
        int frameSize;
    }
    
    using namespace X265_NS;    // for subsequent code that uses those variables
    

    或到

    int X265_NS::frameNumber;
    int X265_NS::frameSize;
    
    using namespace X265_NS;    // for subsequent code that uses those variables
    

    【讨论】:

    • 感谢您的回复。仍然存在错误:如何在我的 cpp 文件中定义向量,因为正在生成“1 unresolved extern”变量错误。其次,正如您告诉我在使用这些变量的后续类中使用上述解决方案,但这会产生“已经定义的错误”。再次感谢您的帮助
    • 我不建议在“后续类”中使用上述解决方案 - 我假设您的意思是您在多个编译单元中复制定义。 C++中有“单一定义规则”。这意味着,在这种情况下,您不能在整个程序中多次定义变量。
    • 当我只在 yuv.cpp 中声明这些变量而不在分析中声明这些变量时,就会产生“未声明的标识符错误”。请告诉我如何在 cpp 文件中定义矢量。
    猜你喜欢
    • 2016-09-18
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多