注册 登录
编程论坛 C++教室

请问一个关于命名空间中变量冲突的问题

blues1207 发布于 2010-04-01 18:00, 796 次点击
#include <iostream>
#include "my.h"
using namespace std;
using namespace myspace;
extern void output();
int main()
{
        output();
        return 0;
}

#include <iostream>
#include "my.h"
using namespace std;
using namespace myspace;
void output()
{
        cout << "verbose = " << verbose << endl;
}


#ifndef _MY_H
#define _MY_H
namespace myspace {
        bool verbose = true;
};
#endif


[xx@localhost cppwork]$ g++ a.cpp b.cpp
/tmp/ccRPtZqX.o:(.data+0x0): multiple definition of `myspace::verbose'
/tmp/ccgNbGeR.o:(.data+0x0): first defined here
collect2: ld returned 1 exit status
我想在a.cpp 和b.cpp中都使用verbose这个变量,但是出现冲突定义问题,请问如何解决,非常感谢!!
4 回复
#2
hahayezhe2010-04-01 19:02
myspace::verbose
#3
yyblackyy2010-04-01 21:27
//test.cpp
#include <iostream>
#include "my.h"
using namespace std;
using namespace myspace;
extern void output();
int main()
{
        output();
        return 0;
}

//********************************
//my.h
#ifndef _MY_H
#define _MY_H
#include <iostream>
namespace myspace {
        bool verbose = true;
};
using namespace myspace;
using namespace std;
void output()
{
        cout << "verbose = " << verbose << endl;
}
#endif
#4
yyblackyy2010-04-02 18:17
#include <iostream>
#include "my.h"
using namespace std;
namespace myspace {                    //添加定义
        bool verbose = true;
};

using namespace myspace;
void output()
{
        cout << "verbose = " << verbose << endl;
}
************************************************************8
#ifndef _MY_H   //这里最好把_MY的_去掉,这样保险些
#define _MY_H
namespace myspace {                 //改成 namespace myspace{};  头文件中因该用声明 不该定义  除了类,常量,和内联函数外
        bool verbose = true;
};
extern void output();   //添加函数声明
#endif


[ 本帖最后由 yyblackyy 于 2010-4-2 18:27 编辑 ]
#5
floppyfuck2010-04-02 19:22
在main函数之前的那个#include "my.h"去掉
1