0

I have the following define:

#define MY_CLASS MyClass

I'm trying to make a macro that will use MY_CLASS to expand to:

#include "MyClass.h"

Something like (according to this answer):

#define MY_CLASS MyClass
#define FILE_EXT h
#define M_CONC(A, B) M_CONC_(A, B)
#define M_CONC_(A, B) A##B
#define APP_BUILD M_CONC(MY_CLASS, M_CONC(.,FILE_EXT))
#include APP_BUILD

That one doesn't work though... I get these 3 errors:

Expected "FILENAME" or <FILENAME>
Pasting formed '.h', an invalid preprocessing token 
Pasting formed 'MyClass.', an invalid preprocessing token

Is it possible to do it somehow?

traveh
  • 2,700
  • 3
  • 27
  • 44
  • Does this approach work for you? [C Macro - Dynamic #include](https://stackoverflow.com/questions/5873722/c-macro-dynamic-include) – sj95126 Oct 22 '22 at 23:44
  • No idea how I missed that question... it's not exactly what I need and it took me a whilte to find out how to get rid of the prefix in the string (the "linux/compiler-gcc" part) but I finally managed with an empty #define. I guess I'll post the answer... – traveh Oct 23 '22 at 03:38
  • Are you sure the effort is worth the result? `#define MY_CLASS_HDR "MyClass.h"` would be a lot simpler for everyone. – Jonathan Leffler Oct 23 '22 at 03:45
  • @JonathanLeffler it's for a generic example of a library written for educational purposes for students that are not familiar with C++ templates yet and I thought it's slighty more elegant than making 2 `#define`'s for them to change (and would also nicely demonstrate some possible complexity of the preprocessor). Probably not gonna change anyone's course of life though :-) – traveh Oct 23 '22 at 03:56

2 Answers2

1

As to your Question: If there's a more elegant / quicker (maybe 1 less macro definition?) solution

#define STRINGIFY(X) #X
#define FILE_H(X) STRINGIFY(X.h)

//usage:

#define MY_CLASS MyClass
#include FILE_H(MY_CLASS)
//expands to: #include "MyCLass.h"

//or

#define ANOTHER_CLASS AnotherClass
#include FILE_H(ANOTHER_CLASS)
//expands to: #include "AnotherClass.h"

Well, if you need concatenation, then you have to add two extra lines:

#define CONCAT(A,B) CONCAT_(A,B)
#define CONCAT_(A,B) A##B

//could be extended like this:
//#define CONCAT3(A,B,C) CONCAT(CONCAT(A,B),C)
//...
Erdal Küçük
  • 4,810
  • 1
  • 6
  • 11
0

I was referred to this post in the comments (thanks @sj95126) which I originally missed. It didn't work as-is but I was able to deduce the right answer from it rather quickly...

This works:

#define MY_CLASS MyClass
#define EMPTY
#define MACRO1(x) #x
#define MACRO2(x, y) MACRO1(x##y.h)
#define MACRO3(x, y) MACRO2(x, y)
#include MACRO3(EMPTY, MY_CLASS)

If there's a more elegant / quicker (maybe 1 less macro definition?) solution I would be happy accept a different answer.

traveh
  • 2,700
  • 3
  • 27
  • 44