I've seen a couple of suggestions to use an enum here but nothing posted here seems to really solve the problem that was asked. The Boost approach is pretty hacky - it uses a massive workaround to redefine a single defined value:
https://github.com/boostorg/preprocessor/tree/master/include/boost/preprocessor/slot
Here's a possible solution using enum:
#define REGISTER_EVENT_HANDLER(name) name,
enum {
#define APP_REGISTER_HANDLERS
#include "main.h"
#undef APP_REGISTER_HANDLERS
APP_MAX_HANDLERS
};
// ...sometime later (not really relevant but might be useful for someone)...
#define IF_RUN_HANDLER(name) if (state == name) {
#define ENDIF_RUN_HANDLER }
#define APP_RUN_HANDLERS
#include "main.h"
#undef APP_RUN_HANDLERS
Inside "main.h":
#include "libfile1.h";
#include "libfile2.h";
#include "libfile3.h";
#include "libfile4.h";
#include "libfile5.h";
...
#include "libfileN.h";
Inside each "libfile#.h" file:
#ifdef APP_REGISTER_HANDLERS
REGISTER_EVENT_HANDLER(my_uniquely_named_event_handler)
#endif
#ifdef APP_RUN_HANDLERS
IF_RUN_HANDLER(my_uniquely_named_event_handler)
...Do something here...
ENDIF_RUN_HANDLER
#endif
As long as the enum entries are uniquely named, they will be given unique IDs, which is kind of what the OP was after. The major feature is to #define
, #include
, and then #undef
the earlier define at the correct points in the code. The same file can be included many times, so triggering portions of the file to emit code at various points allows each file to define multiple outputs based on which #define
is currently active.