c++ - C++从另一个源文件访问已在一个源文件中声明/定义的变量

标签 c++ compiler-errors

我有一个要在名为Spiral.cpp的C++源文件中使用的变量。该变量已使用以下代码在头文件中声明:

struct DataMessage{
    ...
    ::CORBA::Double radius;
    ...
};

内:
namespace STEERDataIDL{
    ...
}

然后使用下面的代码在另一个名为Module.cpp的源文件中给它一个值:
radius = Interface.spiralRadius;

里面case STEERDataIDL::SpiralPattern:
功能的:
void Module::FormList(void){
    ...
    switch (this->InterCDNUSteerData.SteerMode)
{
          ....
      }
}

就像上面的行所暗示的那样,此处赋予变量的值取自GUI上的用户输入。

如前所述,然后我尝试在Spiral.cpp源文件的函数中使用此变量:
void Module::FormList(); /*This is the function in which `radius` was given its value */
if(abs(someDistance) < (Data.radius + x)){
    // Do XYZ
}

但是,我遇到了一些我不理解的编译错误:

error 'module' is not a class or namespace name (on the void Module:: line)

'x' undeclared identifier

left of '.radius' must have class/ struct/ union, type is "unkown type"




谁能向我解释我在这里做错了什么?我需要做什么来解决这些编译错误?

最佳答案

您必须包括在其中声明了Data的头文件,因此,Data的声明应如下所示:

//globals.h
#include "DataMessage.h"
extern DataMessage Data;  //to indicate that Data will be created in a different cpp file and visible to other cpp files

然后,您应该在cpp文件中创建数据,该文件包括在其中声明了变量Data的头文件,该文件看起来像这样:
//globals.cpp
#include "globals.h"
DataMessage Data;

现在,在Module.cpp中,您可能会遇到以下内容:
#include "globals.h"
...
void Module::FormList() {
  Data.radius = Interface.spiralRadius;  //notice how radius is accessible only through the Data variable
}

在Spiral.cpp中,您应该具有以下内容:
#include "globals.h"
...
void Foo() {
  if(abs(someDistance) < (Data.radius + x)) {  //Data.radius is the same one across all files
    // Do XYZ
  }
}

关于c++ - C++从另一个源文件访问已在一个源文件中声明/定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26997658/

相关文章:

actionscript-3 - 带有Flex项目的IntelliJ IDEA错误1172

c++ - int 或 char enum 到 int ,而不是 ASCII

c++ - 重复一段代码固定次数

sql - hive 查询中 “”缺少EOF “”

单独文件中的 C++ 类无法编译。已经在 Class.obj 中定义了一个或多个多重定义的符号

Java - 应该是基本的东西是每行都给出错误

c++ - 类声明错误: insufficient contextual information to determine type

c++ - 在模板编程方面需要一些帮助

c++ - boost-python纯虚拟检测缺失实现

c++ - zlib gzgets 非常慢?