On Linux (glibc), stdout is defined as follows:
extern struct _IO_FILE *stdout;
So, you can do whatever you need.
However, on MinGW, stdout is defined as follows: stdio.h :
#define stdout (&_iob[STDOUT_FILENO])
Alas, you cannot accept the address, and as you have discovered, this is not something you can use in the global initializer. :-(
The root of the problem is that the C standard states that these should be macros, which means that any portable program should not make any assumptions about what's inside. So, I'm afraid there is no easy way to avoid stdout programming programmatically. This is because many libraries require the lib_initialize() function, which must be called first.
C ++ allows constructors for global variables, and they are automatically called before main even for libraries. It is possible with gcc to hack a C program to do the same, but this is an evil trick, and I cannot remember how to do it from the head.
I would just do this:
#include <stdio.h> FILE* fout = NULL; int my_library_function() { if (!fout) fout = stdout; fprintf( fout, "hello\n" ); }
This is not a big performance issue: you still have to load fout , and comparing with zero is pretty cheap.
source share