Question

I have a single global class instance:

myclass.h

class Cmyclass {
public:
  void log(const char* msg);
  void set_file(std::string file);
private:
  std::string file;
};

myclass.cpp

void Cmyclass::log(const char* msg) {
  std::ofstream output_file(file.c_str(), std::ios::app) ;
  output_file << msg << std::endl;
}

void Cmyclass::set_file(std::string file) {
  this->file = file;
}

I use the ‘extern’ keyword in files that need access to the global:

extern Cmyclass myclass;

I would like to eliminate the set_file() method and set the file in the constructor:

Cmyclass::Cmyclass(std::string file) {
  this->file = file;
}

But if I do that, my extern usage above is no longer valid because of the parameters in the constructor. Is it possible to use the extern keyword if my constructor has parameters?

Thank you!

P.S. a little clearificatin here... please note that the code above works and that I instantiate the class elsewhere, but I want to modify my class so that the constructor takes parameters. If that is the case, how is my extern declaration supposed to look like?

Was it helpful?

Solution

As indicated in the comments:

  • extern is a declaration not a definition. It just means that there's a global variable of that type.

So you have in some header file (e.g. Globals.h)

extern Cmyclass myclass;

Now, if you don't want your linker to fail, you must have in some source file (e.g. Globals.C)

Cmyclass myclass;

Now, the above calls the constructor without parameters. If you only have a constructor with parameters, you can replace that (in the source file) with:

Cmyclass myclass=Cmyclass("Some File");

... but the extern declaration remains the same. Think of it this way, other people don't care about how you created the myclass global variable, they're just interested in using it. So the fact that it has parameter-constructor or not only matters when the variable is instantiated (and that happens on the *.C, not on the *.h)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top