configure_file breaks multiline comments

CMake version: 3.20.5 (and older)

I’m not sure if my observation is intended behavior or a bug. I noticed that configure_file()

  • does not check for C (multiline) comments
  • removes all text in a line before #cmakedefine
  • expands #cmakedefine… inside C/C++ comments

Example: ‘#cmakedefine HAVE_JPEG 1’ inside a multiline C comment triggers a compilation error if HAVE_JPEG is false. After expansion the terminating ‘*/’ ends the existing multiline comment which leads to a compilation error in the following line(s).

This was a real case; I was trying to document CMake syntax in the input file.

All examples in the docs show ‘#’ at the beginning of the line. There’s no clue what will happen if it is inside a comment block and whether it is expanded if ‘#’ is not the first character or maybe after optional whitespace.

Please see more details in the attached complete project in text form:
configure_file_breaks_comments.txt (1.7 KB)

(1) Is this behavior intended?
(2) If yes (or no) could (should) this be documented?

Thanks for reading and for any clues.

PS: I mitigated this in my project by replacing ‘#’ with ‘[#]’, hence there’s no problem for me anymore. Please consider this as an attempt to report a bug or trigger improvement of the documentation.

BTW: This code:
// NOT USED: #cmakedefine HAVE_ZLIB 1
gets expanded to:
// NOT USED: #define HAVE_ZLIB 1
(if HAVE_ZLIB is true, obviously)

which I think is at least inconsistent because the leading ‘// comment’ is NOT removed - and removing it would in all cases lead to unexpected behavior.

My suggestion would be to not expand #cmakedefine at all if it’s not the first token (after optional whitespace) in a source line.

Please file an issue. I don’t know that fixing it is all that doable since it would (probably) need to be a policy that probably isn’t all that easy to implement. I think mentioning this behavior as a note in the documentation is certainly the place to start. Any new policy which fixes it can then update that documentation to mention the policy.

Thanks for reading and for your reply.

I’ll file an issue as requested.