c ++中头文件中的命名空间

时间:2013-12-14 09:24:16

标签: c++ namespaces

我对namespases有一个问题。它说“phys1 :: x的多重定义”,为什么?看看我的代码:

的main.cpp

#include <cstdlib>
#include <iostream>
#include "abcd.h"
using namespace phys1;
using namespace std;
int main(){
    cout << "SD " << tits() << endl;
    system("pause");
    return 0;
}

abcd.h

#ifndef _ABCD_H_
#define _ABCD_H_
namespace phys1
{
    double xx = 9.36;
}
double tits();
#endif

abcd.cpp

#include "abcd.h"
double tits(){
    return phys1::xx;
}

1 个答案:

答案 0 :(得分:5)

double xx = 9.36;是一个定义,您无法跨多个翻译单元定义相同的符号。

您可以使用const,它提供变量内部链接,或static

//can't modify the value
const double xx = 9.36;

//can modify the value
//each translation unit has its own copy, so not a global
static double xx = 9.36;

或真正的全球性,外部:

extern double xx;

//cpp file
double xx = 9.36;