Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessing: Is defining a shorthand for `import` legal?

For solving a code-golf challenge, I want to produce the smallest possible code. I had the idea of defining a shorthand for import:

#define I import
I<vector>;

short godbolt example

Of course, the intention here is to reuse I to actually save bytes.

Is this legal in C++20?

Thoughts / What I found out so far:

  • According to cppreference, "The module and import directives are also preprocessing directives". So I think it would boil down to the question whether we have a guarantee that the preprocessor first has to replace I with our definition?
  • I think handling the import directive should happen in translation phase 4, and for the whole phase, I should not be macro-expanded unless specified otherwise ([cpp.pre]-7). Is it specified otherwise for this case?
  • Is it possible this works as part of the preprocessor rescan?
  • Clang and GCC on godbolt do not compile, but AFAIK they don't yet support importing standard library headers without extra steps, and they give the same error message with the shorthand version, which indicates it would work(?)
  • The same approach, but with include instead of import, does not work with gcc and clang and thus probably isn't legal.
like image 647
He3lixxx Avatar asked Oct 15 '25 14:10

He3lixxx


1 Answers

No.

[cpp.pre]/1:

A preprocessing directive consists of a sequence of preprocessing tokens that satisfies the following constraints: At the start of translation phase 4, the first token in the sequence, referred to as a directive-introducing token, begins with the first character in the source file (optionally after whitespace containing no new-line characters) or follows whitespace containing at least one new-line character, and is [...]

Preprocessing-directive-ness is determined at the start of translation phase 4, prior to any macro replacement. Therefore, I<vector>; is not recognized as a directive, and the import from the macro expansion of I is not replaced by the import-keyword token. This in turn means that it is not recognized as a module-import-declaration during translation phase 7, and is instead simply an ill-formed attempt to use the identifier import without a preceding declaration.

The point of this dance is to ensure that build systems can know a file's dependencies without having to fully preprocess the file - which would be required if imports can be formed from macro replacement.

like image 100
T.C. Avatar answered Oct 17 '25 03:10

T.C.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!