1

Hi im looking for a solution for GCC to printf a value which is calculated during compilation.

There is message pragmas but they can only print a user input string. what im looking for is a printf style output where i can input parameters.

example

printf("hi %s, my value is %d\n", "john", 15);

example 2: searching solution for this

void dummy(MyObjectReference & obj)
{
#if(sizeof(obj) != 512)
#pragma message "cannot build, your object size is not 512, it is %d", sizeof(obj)
#error "stop build"
#endif

  obj.do_stuff();

  return obj.get_result();
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
user654789384
  • 305
  • 1
  • 4
  • 21

1 Answers1

4

Hi im looking for a solution for GCC to printf a value which is calculated during compilation.

You cannot do that with a standard GCC 9.

You could consider writing your own GCC plugin providing, for example, some additional #pragma (or GCC builtin) doing what you want.

However, developing such a plugin might take you several weeks of efforts. You'll need to understand GCC internals to code that plugin. So look into GCC resource center.

With C++11 or later, you might use static_assert(sizeof(obj) == 512, "bad size of obj") which works after preprocessing (but won't display sizeof(obj) as an integer).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • 1
    `static_assert` exists in C++11 as well. Note that before C++17, you have to provide a message as well (i.e. `static_assert(sizeof(obj) == 512, "unexpected obj size")`). But this won't solve OP's issue, since said message must be a string literal. – Virgile Jan 30 '20 at 11:21
  • yes i work with static assertions (cpp14). but none of the messages printed in case of failure, be it pragmas, or assertion string, are able to format a string with int parameters as a simple printf. so it should be possible, to tell me something like "static assertion failure, obj is not 512, its acutally just 496 or something. – user654789384 Jan 30 '20 at 14:06
  • You could consider extending GCC with your own plugin. – Basile Starynkevitch Jan 30 '20 at 16:41