如何访问在命名空间中声明的变量到另一个cpp文件中

时间:2015-06-15 10:34:26

标签: c++ namespaces header-files

SpiralTest.h

#ifndef SPIRALTEST_H_
#define SPIRALTEST_H_
namespace eveready
{
 struct TNotes{
  int pie;
  void meth();
 };
 extern TNotes tell;
}
#endif /* SPIRALTEST_H_ */

SpiralTest.cpp

#include "SpiralTest.h"

namespace eveready
{
void TNotes::meth(){
 pie=0;
}
}

现在我尝试将变量 pie 访问到 abc.cpp

abc.cpp

#include "SpiralTest.h"
using namespace eveready;
tell.meth();

但是我编译时显示错误 (.text + 0x49):未定义的引用`eveready :: tell'

我也试过`eveready :: tell.meth();但它再次显示相同的错误。 我该怎么办..?

4 个答案:

答案 0 :(得分:1)

extern TNotes tell;

只是名称tell的声明。您必须在abc.cpp

中定义相应的对象
#include "SpiralTest.h"
using namespace eveready;

//...

TNotes tell;
//..
tell.meth();

考虑到函数调用必须在其他函数中。它可能不在命名空间中。

答案 1 :(得分:0)

您应该重新设计该程序。使用全局变量的意大利面条编程很糟糕。而是使用面向对象的设计(具有一致的代码格式):

SpiralTest.h

#ifndef SPIRALTEST_H_
#define SPIRALTEST_H_
namespace eveready
{
  class TNotes
  {
    private:
      int pie;
    public:
      void meth();
  };
}
#endif /* SPIRALTEST_H_ */

SpiralTest.cpp

#include "SpiralTest.h"

namespace eveready
{
  void TNotes::meth()
  {
    pie=0;
  }
}

abc.cpp

#include "SpiralTest.h"
#include "the_file_where_tell_variable_is_allocated.h"

using namespace eveready;

TNotes tell = some_class_in_that_other_file.get();
tell.meth();

答案 2 :(得分:0)

结构在C ++中已弃用。 您在SpiralTest.h中声明为extern,这意味着编译器认为它将在其他地方分配存储。所以当它在abc.cpp中遇到tell时,链接器会抛出错误。

1)使用类而不是结构。 2)在Spiraltest.cpp或abc.cpp

中定义tell(可能由TNotes类的构造函数)

答案 3 :(得分:0)

没有必要extern你的命名空间的实例,这不是访问命名空间成员的正确方法。这样做的正确方法如下所示。

另一件事是尝试初始化pie的值,使用struct TNotes

的构造函数可以完成相同的操作

以下是包含更改并且按预期工作的文件。

注意:我添加了meth()的定义来测试我的代码。

<强> SpiralTest.h

#ifndef SPIRALTEST_H_
#define SPIRALTEST_H_

namespace eveready
{
  struct TNotes
  {
     int pie;
     void meth();
     TNotes(int x)
     {
        pie = x;
     }
  };
}

#endif /* SPIRALTEST_H_ */

<强> SpiralTest.cpp

#include"SpiralTest.h"
#include<iostream>

using namespace eveready;


void TNotes::meth()
{
   std::cout<<"inside meth";
}

<强> abc.cpp

#include "SpiralTest.h"

using namespace eveready;

int main()
{
TNotes tell(0);
tell.meth();

return 0;
}

如有任何疑问,请随时添加评论。