I am developing a GUI app on WinXP but unfortunately std::cerr/cout goes nowhere. I would like to add a simple debug method that appends messages to a log file.
I have been hashing together an almost workable solution reading other posts. And am able to have a single debug() method call in my GUI app. However, don’t even get that far in the below example app I am trying to use to find a solution.
Using:
- Dev-C++ v4.9.9.2
- WinXP
Below is the structure of my example app:
C:.
| Makefile.win
| Project1.dev
|
\---src
| bar.cpp
| bar.h
| foo.cpp
| foo.h
| main.cpp
|
+---inc
| debug.h
|
\---log
src/bar.h:
#ifndef BAR_H
#define BAR_H
class Bar
{
public:
Bar();
};
#endif
src/bar.cpp:
#include "bar.h"
Bar::Bar()
{
// debug("I am Bar.");
}
src/foo.h and src/foo.cpp are the same except change ‘Bar’ to ‘Foo’
Using information that I have found in other articles…
src/inc/debug.h:
#ifndef MY_DEBUG_H
#define MY_DEBUG_H
#include <iostream>
#include <fstream>
#include <string>
#ifndef LOGFILE
#define LOGFILE std::ofstream logfile("log/debug.txt", std::ios::app);
#endif
#ifndef debug
#define debug(s) LOGFILE << "[" << __DATE__ << " " << __TIME__ \
<< "] " << __FILE__ << ":" << __LINE__ << " " << s << std::endl
#endif
#endif
src/main.cpp:
#include "inc/debug.h"
#include "foo.h"
#include "bar.h"
#include <iostream>
int main (int argc, char **argv)
{
debug("Starting program.");
Foo *f = new Foo();
Bar *b = new Bar();
}
When I attempt to compile this I get an error at the debug("Starting program."); line in main.cpp saying expected primary-expression before '<<' token.
Could someone tell me what causes this error and also a good way to then be able to apply debug messages in other files/classes i.e. uncomment the lines:
// debug("I am Bar.");
// debug("I am Foo.");
in bar.cpp and foo.cpp respectively and use debug() anywhere else?
Thanks for any help.
Your define for logfile is messed up.
When your code is preprocessed you’ll get:
What you would need to do is something like this in a header file:
and in some cpp file (perhaps your main.cpp file):
To disable debugging you could do something like:
When your debug flag isn’t enabled compared to your other debug definition.
You could also put the class initialization in a similar
#ifdefblock to avoid opening the file when you aren’t using it.