简体   繁体   中英

extern constant, unnamed namespace

I have a project that requires "creating a constant variable using an unnamed namespace", and I need to share it with functions in another .cpp file. It said the variable declarations could be in their own file. Use of the extern keyword was mentioned, and I figured out how to use extern, having the var in a header file and declared like extern const char varname; , assigned it a value in my main.cpp, ( const char varname = A; globally above the main function) and was able to use it in the other .cpp file. But I'm not sure how to make use of an unnamed namespace. In an example file they have the following in the main file:

namespace
{
  extern const double time = 2.0;
}

But there's now example of how to access that in another .cpp file. I tried doing that with my variable and I get an error in the other file where I try to use it saying it's not declared in that scope.

Can someone offer some insight as to what I should be doing here to make use of both of these things?

You can access to use it via an other reference to the variable.

For example:

namespace
{
  const double time = 2.0;
  const double & local_ref_time(time); //Create a local referece to be used in this module
}


extern const double & global_ref_time(local_ref_time); //Create the global reference to be use from any other modules

You could try writing an accessor function like so:

main.cpp

#include "other.hpp"

namespace
{
    const double time = 2.0;
}

int main()
{
    tellTime();
    return 0;
}

const double getTime()
{
    return time;
}

other.hpp

#ifndef OTHER_HPP_INCLUDED
#define OTHER_HPP_INCLUDED

const double getTime();
void tellTime();

#endif // OTHER_HPP_INCLUDED

other.cpp

#include <iostream>
#include "other.hpp"

void tellTime()
{
    std::cout << "Time from the anonymous namespace of main.cpp is " << getTime() << std::endl;
}

I don't think any amount of extern will help: https://stackoverflow.com/a/35290352/1356754

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