多个C ++源文件中使用的命名空间

时间:2013-02-20 19:17:41

标签: c++ namespaces extern

我有一个带有.h文件的DLL项目,该文件在命名空间中定义了一个类和相关变量。这是使用VS 2008的Windows XP。虽然很明显,这是一个gstreamer程序: - )

我想在命名空间receiverList中使用变量IPC_RECEIVER,但我想在该命名空间之外查看它,例如,相应的IPC_SENDER命名空间。

// IPC-Receiver..h

#ifndef IPCRECEIVER_H_
   #define IPCRECEIVER_H_

   namespace IPC_RECEIVER
   {  
   ....  class declaration.
   }
   typedef std::list<IPC_RECEIVER::GstReceiver*>             ReceiverList_t;
   typedef std::list<IPC_RECEIVER::GstReceiver*>::iterator   ReceiverListIter_t;

#endif /* IPCRECEIVER_H_ */

然后是一个cpp文件,其中变量g_receiverList在IPC_RECEIVE命名空间中声明,但不在任何类中声明。

// IPC-ReceeiverAPIs.cpp
#include "IPC-Receiver.h"

namespace IPC_RECEIVER
{
   ReceiverList_t    g_receiverList;    // list to track receivers
   ...
}

最后是第三个文件

// IPC-Receiver.cpp

#include "IPC-Receiver.h"

extern ReceiverList_t  g_receiverList;  

namespace IPC_RECEIVER
{
   GstReceiver::GstReceiver()
   {
      g_receiverList.push_back( this );
   }
}

当我编译它时,我收到此错误:

Error   1   error LNK2001: unresolved external symbol 
   "class std::list<class IPC_RECEIVER::GstReceiver *,
   class std::allocator<class IPC_RECEIVER::GstReceiver *> > g_receiverList" 
   (?g_receiverList@@3V?$list@PAVGstReceiver@IPC_RECEIVER@
   @V?$allocator@PAVGstReceiver@IPC_RECEIVER@@@std@@@std@@A)
   IPC-Receiver.obj 

我尝试过在extern和构造函数中添加命名空间名称的各种组合。

IPC_RECEIVER::g_receiverList.push_back( this );

我明白了:

Error   1   error C2039: 'g_receiverList' : is not a member of 
'IPC_RECEIVER'  x:\Projects\IPC-dll\IPC-dll\IPC-Receiver.cpp    54  IPC-dll

并且

extern ReceiverList_t  IPC_RECEIVER::g_receiverList;  

我收到两个错误:

Error   2   error C2039: 'g_receiverList' : is not a member of 'IPC_RECEIVER'   x:\Projects\IPC-dll\IPC-dll\IPC-Receiver.cpp    22    
Error   2   error C2039: 'g_receiverList' : is not a member of 'IPC_RECEIVER'   x:\Projects\IPC-dll\IPC-dll\IPC-Receiver.cpp    55

其中22和54是使用g_receiverList的行。

使用::代替IPC_RECEIVER::也不起作用。

那么,我该如何工作:在一个文件中声明一个名称空间中的变量并在另一个文件中使用它?

这是链接订单问题吗?

1 个答案:

答案 0 :(得分:1)

您需要将extern放在命名空间

namespace IPC_RECEIVER
{
   extern ReceiverList_t    g_receiverList;
}

然后使用不在IPC_RECEIVER命名空间内的代码中的限定名称。

e.g。

void main() {
   IPC_RECEIVER::g_receiverList.push_back(...);
}

在您的示例中,您位于IPC_RECEIVER命名空间中,因此您不需要IPC_RECEIVER::位。