Reputation: 115
I'm creating a windows DLL library that contains a logging class, the log function in that class simply calls fprintf like this for testing purposes:
fprintf(stderr, "DEBUG: %s\n", "Hello");
Now this call works fine if i use it from any function in any file in my other project (that uses the library) but if i put it anywhere in my library with the logging class it simply wont print anything.
I can see it runs the function correctly (using a simple exit(0); to test).
Now i'm still kinda new to the whole Library concept in c/c++ so there might be something i just don't understand, but otherwise i don't know why it doesn't work.
I tried searching here and on google, but i couldn't find anyone else with the same exact problem.
I use VC++ 2010
EDIT: I got the idea of passing the filepointer instead of just using stderr from the library, this causes an exception to be thrown however (the _tmpfname pointer of the file is NULL at the time of the throw, which im not sure is correct)
Upvotes: 2
Views: 1090
Reputation: 400512
I would avoid doing this for any production code (it's ok for testing though). The standard I/O streams belong to the application, and the DLLs are guests in the house. If you want to provide debug output, allow the application to setup a callback function for logging, e.g.:
// In your DLL's header file:
typedef void (*LogFunc)(const char *, ...);
void DLLEXPORT SetLogFunction(LogFunc logFunc);
// In your DLL's source file:
LogFunc g_LogFunc;
void DLLEXPORT SetLogFunction(LogFunc logFunc)
{
g_LogFunc = logFunc;
}
...
// Then, instead of calling fprintf(stderr, "blah"), do this:
g_LogFunc("blah");
If you're just doing this for testing, you can write directly to stderr
, but keep in mind that the DLL and the application must be linked against the same version of the C runtime in order for that to work. The C runtime is itself a DLL, and if your DLL and the application specify different versions of the C runtime, you'll end up loading two separate copies of the C runtime into memory, each with their own idea of what stderr
means. When they're different, bad stuff happens.
In Visual Studio, to set the C runtime library you're using, open up your project settings and go to Configuration Properties → C/C++ → Code Generation → Runtime Library and make sure that both the DLL and the application are set to the exact same value (typically "Multi-threaded DLL (/MD)" or "Multi-threaded Debug DLL (/MDd)", depending on whether you're building a Debug or Release build).
Upvotes: 2