views:

110

answers:

5

In my C++ application I sometimes create different output files for troubleshooting purposes. Each file is created at a different step of our pipelined operation and it's hard to know file came before which other one (file timestamps all show the same date).

I'm thinking of adding a global counter in my application, and a function (with multithreading protection) which increments and returns that global counter. Then I can use that counter as part of the filenames I create.

Is this considered bad practice? Many different modules need to create files and they're not necessarily connected to each other.

+2  A: 

It's not bad practice in general.

In C++, I would write a singleton class that would contain the counter and the multithreaded protection. That would be cleaner and would avoid using global variables like you do in c (you would use class static variables instead).

brickner
Would this singleton class have a static `instance` method to return the singleton by any chance? If so, then it's a global like any other.
Troubadour
["Singletons: Solving problems you didn’t know you never had since 1995"](http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/)
Georg Fritzsche
+1  A: 

I'd personally create a factory for these files that would be in charge of returning the file object. You can have that function (or class) have a static variable for the counter.

wilhelmtell
This is how I typically handle logging. It also makes it easier to provide standard file names, and ensure everything ends up in the same place.
Dennis Zickefoose
+3  A: 

If it's only for debugging, is temporary, and will not be released you can do whatever is quickest and easiest.

If, on the other hand, it's something that's likely to stay in your application long term and possibly sneak into a release then I'd definitely take more time and write a basic file creation module that all your other modules have access to.

Troubadour
A: 

I've generally abandoned global variables of any kind in favor of static member variables. They perform the same function and you can restrict how the static members can be changed and accessed.

andand
He mentioned that the variable would be accessed via a function, rather than simply being a raw `extern int fileCount;` thrown at the top of some include file. Given that all he needs to be able to do is increment it and return a copy, that's likely sufficient.
Dennis Zickefoose
+2  A: 

I think, adding to file name current system time with high enough precision will be cleaner and easier to implement and maintain

//helper function to encapsulate details
string makeFileName(string filename)
{ return filename + getCurrentTime(); }

void MyClass::SomeMethod()
{
   File f = CreateFile(makeFileName("myclassfile"));
   ...
}
Alsk