I’m creating a string utility header for my event structs. It’s meant to be only used for debugging.
The event_string_util.h
header contains a single function:
const char* event_to_string(const event* e);
To avoid dynamic allocation and requiring the caller to free the string, I’m using a global static buffer in event_string_util.c
. All other event string functions have static linkage in event_string_util.c
.
// string buffer to return, NOT THREAD SAFE
static char s_buf[300];
And my event string utility functions write a formatted string in this buffer, and return the buffer address.
const char* keyboard_event_to_string(const keyboard_event* e) {
const char* type_str;
switch (e->type) {
case EVENT_KEYBOARD_KEY_PRESSED: type_str = "EVENT_KEYBOARD_KEY_PRESSED"; break;
case EVENT_KEYBOARD_KEY_RELEASED: type_str = "EVENT_KEYBOARD_KEY_RELEASED"; break;
default:
assert(0);
type_str = "UNKNOWN KEYBOARD EVENT";
break;
}
snprintf(s_buf, sizeof(s_buf), "%s: key %s", type_str, keysym_to_string(e->key_sim));
return s_buf;
}
I read How do I prevent my ‘unused’ global variables being compiled out of my static library? and it mentions that the compiler is not allowed to optimize away global objects.
So, I’m wondering, even if in my code I do not have calls to event_to_string(&e)
, and assuming that the compiler will remove all unused event_to_string
functions, will the s_buf
still be allocated? I understood that I would have to compile this into a static library to remove this. What really happens, and how can I avoid allocating this buffer if event_to_string
is not called?
How to prevent the buffer from being allocated?
3