我在sample.h中声明了以下命名空间
// namespace with identifier
namespace N1
{
int b = 80;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
sample2.cpp还使用sample.h中声明的命名空间
#include <iostream>
#include "sample.h"
using namespace std;
using namespace N1;
void foo(void)
{
cout << "b = " << b << endl;
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,我得到了以下错误
$> g++ sample1.cpp sample2.cpp
/tmp/ccB25lEF.o:(.data+0x0): multiple definition of `N1::b'
/tmp/cchLecEj.o:(.data+0x0): first defined here
Run Code Online (Sandbox Code Playgroud)
让我知道如何解决以及如何实现" namespace std "来避免这个问题?
这不是#ifndef
守卫的问题.
使用extern
头文件为:
//sample.h
namespace N1
{
extern int b; //extern is MUST!
//DONT WRITE : extern int b = 80;
}
Run Code Online (Sandbox Code Playgroud)
然后在.cpp文件中将其定义为:
//sample.cpp
namespace N1
{
int b = 80; //initialization should be here
}
Run Code Online (Sandbox Code Playgroud)
包含保护仅在编译期间有效,但错误发生在链接时.这是因为sample.h包含在两个编译单元中,并且N1::b
在两者中都创建了一个变量.
如果你真的想要一个变量(不是a const
),你必须extern
在头文件中声明它,并在一个单独的编译单元中为它创建一个内存位置:
// sample.h
#ifndef N1
#define N1
namespace N1 {
extern int b;
}
#endif
// sample.cpp
#include "sample.h"
namespace N1 {
int b = 80;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9208 次 |
最近记录: |