Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a type's name at compile time without aborting compilation?

In this question:

Print template typename at compile time

we have a few suggestions regarding how to get typical C++ compilers to print a type's name, at compile time. However, they rely on triggering a compilation error.

My question: Can I get the C++ compiler to print the name of a type without stopping compilation?

In general the answer is "probably not", because a valid program can be compiled into its target object without printing anything anywhere, so I'm asking specifically about GCC and clang, with possible use of preprocessor directives, compiler builtins, or any compiler-specific trick.

Notes:

  • Obviously, the challenge is printing types behind using/typedef statements, template parameter values, variadic templates etc. If the type is available explicitly you could just use something like #message "my type is unsigned long long" (as @NutCracker suggested). But that's not what the question is about.
  • Answers relying on C++11 or earlier are preferred to requiring C++14/17/20.
like image 544
einpoklum Avatar asked Feb 13 '20 08:02

einpoklum


Video Answer


1 Answers

gcc and clang offers some interface for using own plugins which can do nearly everything on different stages from parsing to code generation.

The interfaces are compiler specific and as this a plugin for gcc can not be used for clang or visa versa.

The documentation is havy and there is no chance to go in any detail here, so I only point you to the docs from gcc and clang:

gcc plugin clang plugin

like image 127
Klaus Avatar answered Oct 24 '22 01:10

Klaus