加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C命名空间成员访问不同的文件如何? “namespace std”如何实现

发布时间:2020-12-16 10:52:46 所属栏目:百科 来源:网络整理
导读:我在sample.h中声明了以下命名空间 // namespace with identifiernamespace N1{ int b = 80;} sample1.cpp使用上面的命名空间声明 #include iostream#include "sample.h"using namespace std;using namespace N1;int main(void){ cout "b (in main) = " b en
我在sample.h中声明了以下命名空间

// namespace with identifier
namespace N1
{
    int b = 80;
}

sample1.cpp使用上面的命名空间声明

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

using namespace std;
using namespace N1;

int main(void)
{
    cout << "b (in main) = " << b << endl;
      foo(); //written in sample2.cpp
      return 0;
}

sample2.cpp还使用sample.h中声明的命名空间

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

using namespace std;
using namespace N1;

void foo(void)
{
    cout << "b = " << b << endl;
}

当我编译时,我得到了以下错误

$> g++ sample1.cpp sample2.cpp
/tmp/ccB25lEF.o:(.data+0x0): multiple definition of `N1::b'
/tmp/cchLecEj.o:(.data+0x0): first defined here

让我知道如何解决以及如何实现“namespace std”来避免这个问题?

解决方法

包含保护仅在编译期间有效,但错误发生在链接时.这是因为sample.h包含在两个编译单元中,并且在两者中都创建了变量N1 :: b.
如果你真的想要一个变量(不是const),你必须在头文件中将它声明为extern,并在一个单独的编译单元中为它创建一个内存位置:

// sample.h
#ifndef N1
#define N1
namespace N1 {
    extern int b;
}
#endif

// sample.cpp
#include "sample.h"
namespace N1 {
    int b = 80;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读