Make C++ preprocessor add a character at the end of each line

Viewed 103

I am implementing some compile-time check which should base on a CSV file and I am trying to load it a bit hacky way:

constexpr std::variant<int, const char*> test[] = {
#include "data.csv"
};

where "data.csv" is:

  "a","b","c"
  1,"xyz",1
  2,"abc",0
  3,"def",1

Obviously, there is a problem with the lack of commas at the end of each line. Is there a way to add a comma with C++ (or even Boost) preprocessor at the end of each line?

I know I could add some token at the end of each line and then replace it with #define, but I would like to avoid it for the sake of clarity. Can one replace a \n character with #define?

1 Answers

Is there a way to add a comma with C++ (or even Boost) preprocessor at the end of each line?

Yes, create a macro:

#define ADD_COMMA(...)  __VA_ARGS__ ,

Then change each line of the file to:

  ADD_COMMA("a","b","c")
  ADD_COMMA(1,"xyz",1)
  ADD_COMMA(2,"abc",0)
  ADD_COMMA(3,"def",1)

If by "is there a way to add a comma" you mean reading the file line by line in preprocessor and calling some macro on each line, then no, that is not possible. Such functionality is broadly out-of-scope for a C preprocessor.

BTW your problem looks oddly trivial - just add a comma on the end of each line to the file with an external tool.

Related