C++ preprocesor macro for accumulating comma-separated strings

c++, c-preprocessor

Solution

#include <iostream>
#include <vector>
using namespace std;

vector<const char*>& all()
{
    static vector<const char*> v;
    return v;
}

struct string_register
{
    string_register(const char* s)
    {
        all().push_back(s);
    }
};

#define REGISTER3(x,y,sr) string_register sr ## y(x)
#define REGISTER2(x,y) REGISTER3(x,y,sr)
#define REGISTER(x) REGISTER2(x, __COUNTER__)

REGISTER("foo");
REGISTER("bar");

int main()
{
}

Problem

I need to do the following: ``` const char* my_var = "Something"; REGISTER(my_var); const char* my_var2 = "Selse"; REGISTER(my_var2); ... concst char* all[] = { OUTPUT_REGISTERED }; // inserts: "my_var1, my_var2, ..." ``` REGISTER and OUTPUT_REGISTERED are preprocesor macros. This would be great for large number of strings, like ~100. Is it possible to accomplish this? PS. The code belongs to level-0 "block" – i.e. it is not inside any function. AFAIK, I cannot call regular functions there.

Original source