logological / gpp

GPP, a generic preprocessor
https://logological.org/gpp
GNU Lesser General Public License v3.0
192 stars 33 forks source link

Define a macro to include file not working #60

Closed drriguz closed 1 year ago

drriguz commented 1 year ago

Hi, I'd like to define a macro to include files dynamically, here's a minimal example:

File structure:

- main.txt
\ chapters
  - ch01.txt

main.txt

#define IMPORT(dir,file) #include dir/file

#include chapters/ch01.txt
IMPORT(chapters, ch01.txt)

Then I run gpp main.txt, #include chapters/ch01.txt works as expected, However, the last line, IMPORT(chapters, ch01.txt) won't work, and says that error: Requested include file not found.

It's this a bug or it's something that not supported?

Thanks, Riguz

logological commented 1 year ago

As explained in the manual, arguments to meta-macros (like #include) aren't necessarily evaluated, so in your example, your last line initially expands to #include dir/file instead of #include chapters/ch01.txt.

The Examples section of the manual explains how to get around this using #defeval and some helper macros. See in particular the examples involving the macro APPLY. Here's how you might adapt it to your particular use case:

#define IDENTITY(x) x
#define BUILDIMPORTSTRING(dir,file) \#include dir/file
#define IMPORT(dir,file) IDENTITY(#defeval RUNIMPORTSTRING BUILDIMPORTSTRING(dir,file)
RUNIMPORTSTRING)

IMPORT(chapters,ch01.txt)

Does this solve your problem?

drriguz commented 1 year ago

Yes, it works! Thanks for your help!

It's a little bit hard to get startted, thought it's actually already explained in detail in the manual. A toturial should be helpful for beginners like me :p

logological commented 1 year ago

OK, glad I could help! I agree that a tutorial would be nice. I don't have the time to produce one now but perhaps someone else might step up and volunteer. :)