定義全局外部變量:
在.cpp文件中定義一個命名namespace,然后在.h文件中extern,如:
在App的cpp文件中定義一個
namespace glb
{
int a,b;
//全部變量和函數
}
在APP的h文件中
namespace glb
{
extern int a,b;
//全部變量和函數
}
定義鏈接性為內部的全局變量使用匿名namespace.
示例代碼如下:
1.namespace.h文件
同時演示了名稱空間嵌套
使用名稱空間,演示了使用匿名名稱空間定義鏈接性為內部的全局變量
在.cpp文件中定義一個命名namespace,然后在.h文件中extern,如:
在App的cpp文件中定義一個
namespace glb
{
int a,b;
//全部變量和函數
}
在APP的h文件中
namespace glb
{
extern int a,b;
//全部變量和函數
}
定義鏈接性為內部的全局變量使用匿名namespace.
示例代碼如下:
1.namespace.h文件
#ifndef NAMESPACE_H_
#define NAMESPACE_H_
#include<iostream>
namespace RUNSISI
{
class test
{
public:
test(){}
~test(){}
void print();
};
namespace ms
{
extern const char* str;
}
}
/*namespace ms
{
extern const char* str;
}*/
#endif
2.namespace1.cc#define NAMESPACE_H_
#include<iostream>
namespace RUNSISI
{
class test
{
public:
test(){}
~test(){}
void print();
};
namespace ms
{
extern const char* str;
}
}
/*namespace ms
{
extern const char* str;
}*/
#endif
同時演示了名稱空間嵌套
#include "namespace.h"
namespace RUNSISI
{
namespace ms
{
const char* str="i love u.\n";
}
}
namespace RUNSISI
{
void test::print()
{
std::cout<<"hello namespace.\n";
}
}
3.namespace.ccnamespace RUNSISI
{
namespace ms
{
const char* str="i love u.\n";
}
}
namespace RUNSISI
{
void test::print()
{
std::cout<<"hello namespace.\n";
}
}
使用名稱空間,演示了使用匿名名稱空間定義鏈接性為內部的全局變量
#include "namespace.h"
//using namespace ms;
namespace
{
int b;
}
int main()
{
RUNSISI::test a;
a.print();
b=0;
namespace mr=RUNSISI::ms;
std::cout<<mr::str;
return 0;
}
//using namespace ms;
namespace
{
int b;
}
int main()
{
RUNSISI::test a;
a.print();
b=0;
namespace mr=RUNSISI::ms;
std::cout<<mr::str;
return 0;
}