C++ namespace笔记

最近有一个移植项目,需要将Windows平台的一个项目移植到iOS平台,前提是Windows项目由多个动态库组成,是CC++混合代码,不同的动态库中存在有相同的的文件名,变量名,函数名。而iOS平台的应用只支持静态库,不支持动态库,也就是说必须把Windows项目所有动态库的代码整合到一个iOS工程中,那么重定义等问题就无法避免了。想了一个解决办法,就是利用namespace,已达到不用修改不同文件中同名变量和函数的目的(当然,文件名相同的就需要改文件名了,namespace解决不了这个问题)。但使用的时候还是发现了一个需要注意的地方,那就是namespace中的变量,具体解释见下面代码中的注释部分,范例如下: 

例子中假设一共有5个文件,ClassOne.h, ClassOne.cpp, ClassTwo.h, ClassTwo.cpp,TestNamespace.cpp

 代码如下:

ClassOne.h

// ClassOne.h: interface for the CClassOne class.
//
//

#if !defined(AFX_CLASSONE_H__A95C3A2F_01CB_4791_9F19_26ECAEDE69D2__INCLUDED_)
#define AFX_CLASSONE_H__A95C3A2F_01CB_4791_9F19_26ECAEDE69D2__INCLUDED_


namespace NamespaceClassOne{
#define MARCO_DEMO 1
    extern int var;         // 用extern指定这不是定义.
                            // 不能定义具有外部链接的变量。因为有多个编译单元话,在链接的时候会找到多个定义,链接器无法确定应该链接到哪个定义上因此报错。
    const int constVal = 1; // 但可以定义常量,因为常量是内部链接。

    int Func();
}

#endif // !defined(AFX_CLASSONE_H__A95C3A2F_01CB_4791_9F19_26ECAEDE69D2__INCLUDED_)


 

ClassOne.cpp

// ClassOne.cpp: implementation of the CClassOne class.
//
//

#include "stdafx.h"
#include "ClassOne.h"

namespace NamespaceClassOne{
    int var;
    int Func()
    {
        return 1;
    }
}


 

ClassTwo.h

// ClassTwo.h: interface for the CClassTwo class.
//
//

#if !defined(AFX_CLASSTWO_H__7119FA49_C5C4_454B_8C1E_6560783FBF94__INCLUDED_)
#define AFX_CLASSTWO_H__7119FA49_C5C4_454B_8C1E_6560783FBF94__INCLUDED_


namespace NamespaceClassTwo{
    #define MARCO_DEMO 1
     extern int var;
     int Func();
};



#endif // !defined(AFX_CLASSTWO_H__7119FA49_C5C4_454B_8C1E_6560783FBF94__INCLUDED_)


 

ClassTwo.cpp

// ClassTwo.cpp: implementation of the CClassTwo class.
//
//

#include "stdafx.h"
#include "ClassTwo.h"

namespace NamespaceClassTwo{

    int var;

    int Func()
    {
        return 2;
    }
}


TestNamespace.cpp

// TestNamespace.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "ClassOne.h"
#include "ClassTwo.h"

using namespace NamespaceClassOne;
int main(int argc, char* argv[])
{
     int a = Func();
     var = a;
 
 
     int b = NamespaceClassTwo::Func();
     NamespaceClassTwo::var = b;

	return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值