I have a struct defined in a header as follows:
#define LC_ERR_LEN 300
typedef struct dLC_ERRMSG {
short nr;
short strategy;
char tx[LC_ERR_LEN];
} LC_ERRMSG;
Which I use in my code as such:
LC_ERRMSG err;
char *szError;
szError = strerror(sStatus);
snprintf(err.tx,LC_ERR_LEN," %s - %s",szFilename,szError);
/* do something with our error string */
That works. If however, I declare LC_ERRMSG err; globally – i.e. outside the function it is used, or even extern LC_ERRMSG err; (which was my original intention, as I would want to be able to read out the error status in a central location), the code segfaults at the snprintf call.
Can you give me any clues why?
ddd tells me that the memory is initialized to either all zeroes when declared globally, or at least initialized and readable when declared extern. The values szFilename, szError and LC_ERR_LEN are all correct and meaningful.
Your linker can simply throw away the symbols, which it believes are not used (the GNU linker does so). In this case you can explicitly link the object file with that symbol.
With C++ you can not control the order of initialization of global objects defined in other compilation units without any additional efforts (see http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12).
Use the “construct on first use” idiom, which simply means to wrap your static object inside a function.