简体   繁体   中英

namespaces in headers in c++

I have one problem with namespases. It says "Multiple definition of phys1::x", why? Take a look at my code:

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;
}

double xx = 9.36; is a definition, and you can't define the same symbol across multiple translation units.

You can use a const , which gives the variable internal linkage, or a 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;

or for a true global, extern:

extern double xx;

//cpp file
double xx = 9.36;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM