I have a macro that I would only like to be called at file scope. It would be great if it could complain somehow (at compile time, or at runtime) if it is used within a function. Is this possible?
EDIT: To respond to comments so far: I have static objects that are used repeatedly in my codebase. I have created macros to make creating these objects faster to type, as these objects are used all over the place, to the point where saving keystrokes matters for productivity / annoyance.
Up until this point, I had been creating these objects as static within functions. Recently discovered that this is not thread safe. I'm deciding to move all of these objects out of functions so they are created at program start rather than lazily. I just thought it might be nice to have a failsafe to prevent this bug from popping up again in the future.
To be clear- this isn't holding back progress at all. It's just something I thought would be a nice addition to the macro if it is easy / possible.
What you're looking for is a construct that works at the file level but not at the function level. Off the top of my head, namespaces should fit the bill.
#define FOO(x) namespace { x }
FOO(int bar = 42;) // Compiles
void f() {
FOO(int bar = 42;) // Doesn't compile
}
Since I don't know exactly what you're trying to wrap, I kept this macro as simple as possible. Any actual implementation should use the standard macro creation tricks to make sure it's nice and safe.
Note that anonymous namespaces will make it so every object created within it are only visible to the current compilation unit. In your case, this should not be an issue because your object used to be declared at the function level and were therefor not visible outside the current compilation unit.